En Wed, 05 Sep 2007 02:15:52 -0300, Alex Martelli <[EMAIL PROTECTED]> escribi�:

> xkenneth <[EMAIL PROTECTED]> wrote:
>    ...
>> What I'd like to do, is define a base class. This base class would
>> have a function, that gets called every time another function is
>> called (regardless of whether in the base class or a derived class),
>> and prints the doc string of each function whenever it's called. I'd
>> like to be able to do this without explicitly specifying the function
>> inside all of the other functions of a base class or derived class.
>
> So you need to write a metaclass that wraps every function attribute of
> the class into a wrapper performing such prints as you desire. [...]
>
> import inspect
> class MetaWrapFunctions(type):
>     def __init__(cls, name, bases, attrs):
>         for k, f in attrs.iteritems():
>             if inspect.isfunction(f):
>                 attrs[k] = make_printing_wrapper(f)
>         type.__init__(cls, name, bases, attrs)
>
> Should behave as you described.  I have not tested the code I'm
> suggesting (so there might be some errors of detail) but the general
> idea should work.

After playing a bit with the code I found a problem, __init__ is too late,  
changes to `attrs` are not reflected in the class namespace. Using __new__  
instead is OK. The metaclass should be then:

import inspect
class MetaWrapFunctions(type):
     def __new__(cls, name, bases, attrs):
         for k, f in attrs.iteritems():
             if inspect.isfunction(f):
                 attrs[k] = make_printing_wrapper(f)
         return super(MetaWrapFunctions, cls).__new__(cls, name, bases,  
attrs)

[another way would be to keep __init__ but using setattr(cls, k,  
wrapper(...)]

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to