0

How can I get the class of the method that is wrapped by a decorator with Python 2.7?

With this code:

def timeit(method): def timed(*args, **kw): result = method(*args, **kw) className = ??? print '%s.%s'%(className, method.func_name) #want printed: Test.run return result return timed class Test(object): @timeit def run(self, ): print 'run' a = Test() a.run() 

I'm not sure what to put for className = ???. I want it to print Test.run.

I've seen similar solutions that use im_class and __ self__ but I don't have either.

0

1 Answer 1

4

You could just analyze the self argument to the method.

def timeit(method): def timed(self, *args, **kw): result = method(self, *args, **kw) className = type(self).__name__ print '%s.%s'%(className, method.func_name) #want printed: Test.run return result return timed class Test(object): @timeit def run(self): print 'run' a = Test() a.run() 

If it's a classmethod then you could use two decorators (ie @classmethod @timeit) and get the name via cls.__name__ (where cls is the first argument to timed instead of self).

If it's a staticmethod you will have to turn it into a classmethod in order to be able to get a parameter with class info available.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.