How to replace the metaclasses of all the classes imported

Michele Simionato mis6 at pitt.edu
Wed Jun 4 10:12:31 EDT 2003


janeaustine50 at hotmail.com (Jane Austine) wrote in message news:<ba1e306f.0306031034.1d9df7a1 at posting.google.com>...
> 
> Let me explain more about what I want:
> 
> Let's assume there are a dozen of modules in my program.
> ##############################
> #main.py
> 
> import alpha
> 
> class A:
>     ....
> 
> class B:
>     ....
> 
> def main(...):
>     ....
>     temp=alpha.C()
>     ....
> 
> if __name__=='__main__':
>     main(...)
> 
> ##############################
> #alpha.py
> 
> import beta
> 
> class C:
>     ....
> 
> def ...
> 
> ##############################
> #beta.py
> 
> class D:
>     ....
> 
> def ...
> 
> ----------------------------------
> What I'd like to do with metaclasses is, for example, log all
> method calls with minimum code change.

Two ideas:

1. The poor man solution: if all classes are old style classes, as it
seems
from your example, simply add on top of each module the line
__metaclass__=LoggerMetaclass (you can also do that automatically, if
there are too many modules). 

If this is too much a change of the source code, or if you have new
style classes, then

2. The rich man solution: redefine the __import__ function by using an
improved
version of import_with_metaclass. I suggest to look at
Demo/imputil/knee.py
in the Python source distribution for hints on how to do it.

Note for David Mertz: we should fix the import_with_metaclass function
to
make it safe under meta-type conflicts. I hadn't time to look at it
yet :-(


                                               Michele




More information about the Python-list mailing list