meta classes
anton muhin
antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru
Tue Sep 30 03:37:49 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..
>
>
> ---
>
Really simple example:
class Hooker(object):
class __metaclass__(type):
def __new__(cls, name, bases, members):
def make_wrapper(f):
def wrapper(self):
print "before"
f(self)
print "after"
return wrapper
new_members = {}
for n, f in members.iteritems():
if not n.startswith('__'):
new_members[n] = make_wrapper(f)
else:
new_members[n] = f
return type.__new__(cls, name, bases, new_members)
class Child(Hooker):
def foo(self):
print "Child.foo"
c = Child()
c.foo()
hth,
anton.
More information about the Python-list
mailing list