应用装饰器后如何打印python代码?

时间:2019-09-08 21:15:26

标签: python

我正在尝试了解一个复杂的python装饰器,我想在装饰器应用后查看生成的python代码 ,即python具有后,包装函数的实际python代码应用装饰器。这可能吗?

我以为我可以用inspect来做到这一点,但没有得到我期望的结果。我尝试将代码放入模块中,然后使用print(inspect.getsource(module_name))进行导入,但这会使用@decorator打印原始源代码,而不是应用装饰器后的包装函数。

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_whee():
    print("Whee!")

say_whee()

在python运行之前,上面的结果类似于下面的代码。在上面的装饰器应用后,我想查看结果函数的代码

def say_whee2():
    print("Whee!")

def say_whee_decorated():
    print("Something is happening before the function is called.")
    say_whee2()
    print("Something is happening after the function is called.")

say_whee_decorated()

由于say_whee_decorated(),我希望看到类似inspect.getsource()的内容,但是却得到了:

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_whee():
    print("Whee!")

1 个答案:

答案 0 :(得分:1)

我可以看到您的要求,但我认为您误解了装饰器(和inspect.getsource()的性质),他们没有创建用于包装函数的新代码,而是只是传递了装饰函数进入装饰代码并执行它,不会创建任何中间代码,因此您不应期望看到任何中间代码。