meta classes

Nicodemus nicodemus at globalite.com.br
Mon Oct 6 03:00:53 EDT 2003


Carlo v. Dango wrote:

> hello there
>
> I'd like to take control over the method dispatching of every subclass 
> of a given python class. Currently I've redefined __getattribute__() 
> so i can find the right instance/method to dispatch to. This works 
> fine, albeit it may seem a bit hackish. Further I want to control the 
> actual dispatching, so that I can execute methods before, after or 
> instead of the actual method. I would prefer to do this with the least 
> modification of the source due to debug'ing issues. My best idea so 
> far is to rename every method who subclass the magic class X and then 
> create new methods in place of the renamed ones, which looks up in a 
> list to execute "before-methods", then execute the renamed method etc..
>
> Only I don't know how to do this. I've found some MOP code which was 
> designed for python old-style objects... but this is not what I want. 
> Can anyone kindly give me some pointers for help or some actual code?
>
> many thanks in advance..


You don't need metaclasses at all, actually. I attached the action 
module that I created at work. You can set callbacks in any class:

 >>> import action
 >>> class C:
...     def foo(self, arg):
...             print 'C.foo(%s)' % arg
...
 >>> c = C()
 >>> def callback(arg):
...     print 'callback(%s)' % arg
...
 >>> action.after(c.foo, callback) # will call callback whenever c.foo 
is called
 >>> c.foo(10)
C.foo(10)
callback(10)


Besides after(), you have also before(). Also there's result(), where 
the callback receives as parameter the return of the given function.

HTH,
Nicodemus.


       


-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: action.py
URL: <http://mail.python.org/pipermail/python-list/attachments/20031006/85250c82/attachment.ksh>


More information about the Python-list mailing list