Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #15564
| From | "Russell E. Owen" <rowen@uw.edu> |
|---|---|
| Subject | Decorator question: prefer class, but only function works |
| Date | 2011-11-10 13:52 -0800 |
| Organization | University of Washington |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.2626.1320962112.27778.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Decorator question: prefer class, but only function works "Russell E. Owen" <rowen@uw.edu> - 2011-11-10 13:52 -0800
csiph-web