How to wrap a class's methods?
Steven Bethard
steven.bethard at gmail.com
Sun Feb 20 15:13:22 EST 2005
rbt wrote:
> Jeff Shannon wrote:
>
>> You could probably also do this as a factory function, rather than as
>> a class (also untested!):
>>
>> def Wrapper(func):
>> def wrapped(self, *args, **kwargs):
>> s, r = func(self, *args, **kwargs)
>> if s != 'OK':
>> raise NotOK((s,r))
>> return r
>> return wrapped
>>
>> I believe that this will be semantically almost equivalent, but
>> conceptually slightly simpler.
>>
>> Jeff Shannon
>
> This is a nice example. I have used sub-functions (functions within
> functions) recently with some code, but I've wondered how proper it is
> to do this. Is this type of thing frowned upon?
Nope. If it was frowned upon, Python wouldn't support it. ;) Sometimes
it's even faster:
-------------------- test.py --------------------
def wrapper(func):
def wrapped(*args, **kwargs):
return bool(func(*args, **kwargs))
return wrapped
class Wrapper(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return bool(self.func(*args, **kwargs))
-------------------------------------------------
$ python -m timeit -s "import test; w = test.wrapper(sum)" "w([]); w([1,2])"
100000 loops, best of 3: 4.77 usec per loop
$ python -m timeit -s "import test; w = test.Wrapper(sum)" "w([]); w([1,2])"
100000 loops, best of 3: 6.52 usec per loop
Personally, I still tend towards the class-based version, but I'm sure
in many cases the nested function version would work just as well.
STeVe
More information about the Python-list
mailing list