[Python-ideas] Default decorator?

Christian Heimes lists at cheimes.de
Thu Jan 17 02:05:40 CET 2008



Guido van Rossum wrote:
> Peter Norvig suggested an idea to me over lunch: a "default
> decorator". This would be something you could set once per module and
> it would be invoked for each function definition in the same way as a
> decorator is invoked, before any explicit decorators. His use case was
> something that wraps every function that uses argument annotations
> with something that interprets those annotations in a certain way and
> enforces that interpretation. It would save having to explicitly
> annotate every function or method that way.
> 
> Thoughts? I suggested that a metaclass could do this for methods, but
> that of course leaves plain functions in the lurch.

Is it really required? As it is trivial to write a meta class to
decorator all members of a class, it is also trivial to write a function
which accepts a module name and decorate all functions in the module.

def decorate_functions(decorator, modname):
    function = type(decorate_functions)
    namespace = sys.modules[modname].__dict__
    for name, obj in namespace.items():
        if isinstance(obj, function):
            namespace[name] = decorator(obj)

decorate_functions(somefunc, __name__)


Does a default decorator also decorate nested functions (function with
functions)? And does it also decorate class members or function created
with exec()? What about lambda?

Christian




More information about the Python-ideas mailing list