Using descriptors to wrap methods

From: Edward C. Jones (edcjones_at_erols.com)
Date: 04/26/04


Date: Mon, 26 Apr 2004 07:57:32 -0400

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

------
#! /usr/bin/env python

# Modified from Python Cookbook entry 91192, "eiffelmethod" by Andres
# Tuells. The url is
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/91192

class MethodWraper(object):
     def __init__(self, method):
         self.method = method
     def __get__(self, inst, type=None):
             result = wrapper(inst, self.method)
             setattr(inst, self.method.__name__, result)
         return result

class wrapper:
     def __init__(self, inst, method):
         self.instance = inst
         self.method = method

     def __call__(self, *args, **kargs):
         print 'pre'
         result = apply(self.method, (self.instance,) + args, kargs)
         print 'post'
         return result

def test():
     class C:
         def f(self, arg):
             print 'in f'
             return arg+1
         f = MethodWraper(f)

     c = C()
     print c.f(1)

if __name__=='__main__':
     test()
------