Is there a way to get the function a decorator has

2019-04-10 04:18发布

Suppose I have

@someDecorator
def func():
   '''this function does something'''
   print 1

Now, the object func is an instance of someDecorator. Is there some way I can access the function it holds, i.e something like func.getInnerFunction().

For instance, if I need to retrieve the doc string of func().

5条回答
Summer. ? 凉城
2楼-- · 2019-04-10 04:27

See functools.wraps: http://docs.python.org/library/functools.html. The decorator gets the name and doc string of the original function. You use it like this:

def decorator(f):
    @functools.wraps(f)
    def wrapper():
        ....
查看更多
Luminary・发光体
3楼-- · 2019-04-10 04:32

Are you looking for something along these lines?

>>> def dec(f):
    def inner():
        print(f.__doc__)
    return inner

>>> @dec
def test():
    """abc"""
    print(1)


>>> test()
abc

You're passing function explicitly to the decorator, of course you can access it.

查看更多
Emotional °昔
4楼-- · 2019-04-10 04:35

You can attach the wrapped function to the inner function

In [1]: def wrapper(f):
   ...:     def inner():
   ...:         print "inner"
   ...:     inner._orig = f
   ...:     return inner
   ...: 

In [2]: @wrapper
   ...: def foo():
   ...:     print "foo"
   ...:     
   ...:     

In [3]: foo()
inner

In [4]: foo._orig()
foo
查看更多
太酷不给撩
5楼-- · 2019-04-10 04:38

SilentGhost and sri have partial answers for how to deal with this. But the general answer is no: there is no way to get the "wrapped" function out of a decorated function because there is no requirement that the decorator wrap the function in the first place. It may very well have returned an entirely unrelated function, and any references to your original may have already been garbage collected.

查看更多
手持菜刀,她持情操
6楼-- · 2019-04-10 04:41

You can try using the undecorated library:

With your example func, you could simply do this to return the original function:

undecorated(func)
查看更多
登录 后发表回答