execute a function before and after any method of a parent class

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Oct 3 15:23:28 EDT 2008


En Fri, 03 Oct 2008 11:03:22 -0300, TP <Tribulations at paralleles.invalid>  
escribió:

> I would like to be able to specialize an existing class A, so as to  
> obtain a
> class B(A), with all methods of B being the methods of A preceded by a
> special method of B called _before_any_method_of_A( self ), and followed  
> by
> a special method of B called _after_any_method_of_A( self ).
>
> The goal is to avoid to redefine explicitly in B all methods of A.
>
> Is this possible in Python?

Sure. After reading this (excelent!) article by M. Simionato  
http://www.phyast.pitt.edu/~micheles/python/documentation.html you should  
be able to write a decorator to make any method into a "sandwich"  
(probably based on his "trace" example). Your code would look like this:

@decorator
def sandwich(f, self, *args, **kw):
     self.before()
     f(self, *args, **kw)
     self.after()

class A:
   @sandwich
   def foo(self):
     ...

   @sandwich
   def bar(self, x):
     ...

Ok, but then you have to explicitely decorate every method. To avoid this,  
you may use a metaclass; this article by Michael Foord explains how:
http://www.voidspace.org.uk/python/articles/metaclasses.shtml#a-method-decorating-metaclass

That's all!

-- 
Gabriel Genellina




More information about the Python-list mailing list