Using descriptors to wrap methods

Duncan Booth me at privacy.net
Mon Apr 26 08:40:23 EDT 2004


"Edward C. Jones" <edcjones at erols.com> wrote in 
news:408cfa5a$0$28920$61fed72c at news.rcn.com:

> Here is a stripped-down version of a Python Cookbook recipe. Is there a 
> simpler, more Pythonical, natural way of doing this?

Here's a simpler way of doing the same thing:

>>> def MethodWrapper(f):
        def wrapper(self, *args, **kw):
            print 'pre'
            result = f(self, *args, **kw)
            print 'post'
            return result
        return wrapper

>>> class C(object):
        def f(self, arg):
            print 'in f'
            return arg+1
        f = MethodWrapper(f)

        
>>> c = C()
>>> print c.f(1)
pre
in f
post
2
>>>

Or if you want pre and post code customisable you might try:

>>> def MethodWrapper(f, pre=None, post=None):
        def wrapper(self, *args, **kw):
            if pre: pre(self, *args, **kw)
            result = f(self, *args, **kw)
            if post: post(self, result, *args, **kw)
            return result
        return wrapper

>>> class C(object):
        def pre_f(self, arg):
            print 'pre',arg
        def post_f(self, res, arg):
            print 'post',res,arg
        def f(self, arg):
            print 'in f'
            return arg+1
        f = MethodWrapper(f, pre_f, post_f)

        
        
>>> c = C()
>>> c.f(1)
pre 1
in f
post 2 1
2
>>> 

I don't know if you could call it Pythonic though.



More information about the Python-list mailing list