Decorate a function after defining it?

I think the answer is no, but I cannot find a final statement. I have the following situation:

def decorated_function(function):
    @functools.wraps(function)
    def my_function():
        print "Hello %s" % function.__name__
    return my_function

for attr, value in dct.iteritems():
    dct[attr] = decorated_function(value)

And I really want something like:

def my_function(function):
    print "Hello %s" % function.__name__

for attr, value in dct.iteritems():
    dct[attr] = functools.wraps(my_function, value)

to remove the tangled shell of a decorated function. Can decorators be used only when defining a function?

+4
source share
1 answer

You can decorate functions after they have been defined. In fact, function decorators are just syntactic sugar. For example, you can replace

@classmethod
@synchronized(lock)
def foo(cls):
    pass

with

def foo(cls):
    pass
foo = synchronized(lock)(foo)
foo = classmethod(foo)

See https://www.python.org/dev/peps/pep-0318/ for more details .

+11
source

All Articles