我想打印为my_func,并将源代码,由my_decorator包裹,如何获取由装饰器包装的函数的源代码?
import inspect
from functools import wraps
def my_decorator(some_function):
@wraps(some_function)
def wrapper():
some_function()
return wrapper
@my_decorator
def my_func():
print "supposed to return this instead!"
return
print inspect.getsource(my_func)
然而,对于包装返回源来代替:
@wraps(some_function)
def wrapper():
some_function()
是否有它打印的一种方式取而代之?
def my_func():
print "supposed to return this instead!"
return
请注意,上述内容是从更大的程序中抽象出来的。当然,我们可以在这个例子中摆脱装饰器,但这不是我正在寻找的。
对于Python 2,岂不也比较容易编写自己的'包装()'装饰者,d定义了“便利”属性?看起来这样的代码可能在Python 3中工作,即使没有必要(即它可以移植)? – martineau
@martineau:提供您控制装饰器的源代码,当然可以轻松地更换'wrapps()'实现。你可能也可以修补'functools.update_wrapper'。 –