Decorate a function after it is defined?

无人久伴 提交于 2020-01-03 11:03:05

问题


I think the answer is no, but I can't seem to find a definitive claim. 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 what I really want is 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 confusing shell of decorated_function. Are decorators only possible to apply when the function is defined?


回答1:


You can decorate functions after they have been defined. In fact, function decorators are only 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 details.



来源:https://stackoverflow.com/questions/28741965/decorate-a-function-after-it-is-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!