Sort of an odd way to debug...

Alex Martelli aleax at
Wed Sep 5 07:15:52 CEST 2007

xkenneth <xkenneth at> 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.  The
metaclass will be inherited by subclasses (unless metaclass conflicts
intervene in multiple-inheritance situation).

You don't appear to need the printing-wrapper to be a method, and it's
simpler to have it be a freestanding function, such as:

import functools
def make_printing_wrapper(f):
    def wrapper(*a, **k):
        print f.__doc__
        return f(*a, **k)
    return wrapper

Now, the metaclass could be, say:

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)

and the base class:

class Base:
    __metaclass__ = MetaWrapFunctions

Now, the code:

> class Derived(Base):
>     """This function prints something"""
>     def printSometing(something)
>          #ghost function get's called here
>          print something
> Output would be:
> This function prints something
> something

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.


More information about the Python-list mailing list