AOP and metaclasses ['LBBW': checked]

Holger Joukl Holger.Joukl at
Fri Feb 20 16:43:49 CET 2004

Can you do like that with metaclasses, at runtime I mean?
Maybe you could use another approach, taken from the python cookbook,
functionality to a class (see

>>> import new, types
>>> class UserClass:
...     def method1(self, a):
...         self.m1 = a
...     def method2(self):
...         print "UserClass.method2"
...     def show(self):
...         print self.m1
>>> def enhance(klass, methodName, replacer):
...     method = getattr(klass, methodName)
...     setattr(klass, methodName, new.instancemethod(lambda *args,
**kwargs: apply(replacer, (method, ) + args, kwargs), None, klass))...
>>> def logcalls(meth, self, *args, **kwargs):
...     print "calling", meth
...     return meth(self, *args, **kwargs)
>>> def enhance_all(klass, with):
...     for name, attr in klass.__dict__.items():
...         if isinstance(attr, types.FunctionType):
...             enhance(klass, name, logcalls)
>>> enhance_all(UserClass, logcalls)
>>> u = UserClass()
>>> u.method1(234)
calling <unbound method UserClass.method1>
>>> u.method2()
calling <unbound method UserClass.method2>

Im trying to use AOP techniques on python but, even if I understand
the idea behind metaclasses, I cant find a way to use AOP in a dynamic

What im trying to do is to weave an aspect to a class at runtime, but
i don't want to include any special code or definition in the class
itself. Also, i want to do
it just for some particular classes. Is there any way to do this?

I know its possible to apply an aspect to all the classes by
redefining __metaclass__, and that I can do the same with a single
class by assigning to __metaclass__ inside the class definition.
However, I want to avoid the last step, so i can apply the aspect to
any class.


saludos! santiago.

Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene
Empfänger sind oder falls diese E-Mail irrtümlich an Sie adressiert wurde,
verständigen Sie bitte den Absender sofort und löschen Sie die E-Mail
sodann. Das unerlaubte Kopieren sowie die unbefugte Übermittlung sind nicht
gestattet. Die Sicherheit von Übermittlungen per E-Mail kann nicht
garantiert werden. Falls Sie eine Bestätigung wünschen, fordern Sie bitte
den Inhalt der E-Mail als Hardcopy an.

The contents of this  e-mail are confidential. If you are not the named
addressee or if this transmission has been addressed to you in error,
please notify the sender immediately and then delete this e-mail.  Any
unauthorized copying and transmission is forbidden. E-Mail transmission
cannot be guaranteed to be secure. If verification is required, please
request a hard copy version.

More information about the Python-list mailing list