Get decorated function object by string name

浪尽此生 提交于 2019-12-13 00:55:25

问题


def log(func):
    def wraper(*a, **kw):   
        return func(*a, **kw)
    return wraper

@log
def f():
    print 'f'


print locals()['f'] # - prints <function wraper at 0x00CBF3F0>.

How do you get the real f object (not decorator wrap)?


回答1:


You don't.1 Store it if you need to access it later.

def log(func):
  def wrapper(*a, **kw):
    return func(*a, **kw)
  wrapper.func = func
  return wrapper

@log
def f():
  print 'f'

print f.func

1 You could mess with the closure, but I can't recommend it.




回答2:


The functools module also provides a wraps decorator which makes sure that the wrapped function looks more like the real function: correct name, module, and docstring, for example.




回答3:


If you're running python 3.2 or above, and you use functools.wraps then you will find the wrapped function on the __wrapped__ attribute:

from functools import wraps

def log(func):
    @wraps(func)
    def wrapper(*a, **kw):
        return func(*a, **kw)
    return wrapper

@log
def f():
    print 'f'

print f.__wrapped__

functools.wrapsis a convenience function for decorating a decorated function with the function that does all the work, including adding this attribute functools.update_wrapper.



来源:https://stackoverflow.com/questions/2413271/get-decorated-function-object-by-string-name

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