Applying a decorator to a module

Arnaud Delobelle arnodel at
Thu Nov 27 21:28:43 CET 2008

lkcl <luke.leighton at> writes:

> On Nov 27, 7:43 pm, s... at wrote:
>>     lkcl> Very simple question: how do you apply a decorator to an entire
>>     lkcl> module?
>> Function-by-function or class-by-class.  There is no decorator support for
>> modules.
> awWww!  i'm going to quietly throw my toys out of my pram.
> ... but seriously - doesn't that strike people as... a slightly odd
> omission?
> l.

You can do something like this:

def decorate_functions(decorator, module):
    Function = type(lambda:0), type(len)
    for name, obj in module.__dict__.iteritems():
        if isinstance(obj, Function):
            setattr(module, name, decorator(obj))


>>> def trace(f):
...     def decorated(*args, **kwargs):
...         print 'calling', f.__name__
...         return f(*args, **kwargs)
...     return decorated
>>> import math
>>> decorate_functions(trace, math)
>>> math.log(math.tan(math.pi/4))
calling tan
calling log


More information about the Python-list mailing list