Applying a decorator to a module

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


lkcl <luke.leighton at googlemail.com> writes:

> On Nov 27, 7:43 pm, s... at pobox.com 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))

Example:

>>> 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
-1.1102230246251565e-16

-- 
Arnaud



More information about the Python-list mailing list