Decorator question: prefer class, but only function works

Russell E. Owen rowen at uw.edu
Thu Nov 10 16:52:17 EST 2011


I am trying to write a decorator that times an instance method and 
writes the results to a class member variable. For example:

def timeMethod(func):
    def wrapper(self, *args, **keyArgs):
        t1 = time.time()
        res = func(self, *args, **keyArgs)
        duration = time.time() - t1
        self.timings[func.__name__] = duration
        return res
    return wrapper

This works, but I'm not very happy with the way self.timings is obtained.


I first tried to write this as a class (for readability), and this did 
NOT work:

class timeMethod(object):
    def __init__(self, func):
        self.func = func
    def __call__(self, *args, **keyArgs):
        t1 = time.time()
        res = self.func(*args, **keyArgs)
        duration = time.time() - t1
        args[0].timings.set(self.func.__name__, duration)
        return res

In the first case the wrapper is called as an unbound function, so it 
works. But in the second case the wrapper is called as a bound method -- 
thus args[0] is not func's class instance, and I can't get to the 
timings attribute.

Unfortunately they are both pretty ugly. Is there a cleaner way to 
access the the instance of which func is a member? I was very 
disappointed it was not available when timeMethod was 
called/instantiated.

-- Russell




More information about the Python-list mailing list