"Wrapping" Functions in classes

Gordon McMillan gmcm at hypernet.com
Thu Jul 8 17:59:45 EDT 1999


Aaron Rhodes wrote:

> How do I wrap the methods in a class so that before
> they are called, another function gets called first.
> Is there a special __variable__ that I can use?
> This other function should be called for each of the
> methods in the class.

If you have the source distribution, look at Demo/metaclasses, 
specifically Trace.py.

You don't really need to use a metaclass though. Create a Proxy class 
which wraps your instances. Override __getattr__ to look up the 
attribute in the wrapped instance. If the type of the attribute is a 
types.Functiontype, wrap it in something like the TracingWrapper 
from the above mentioned Trace.py. Then the wrapped function's 
__call__ method is where you put your before / after code (and the 
apply, of course).

- Gordon




More information about the Python-list mailing list