如何在 Python 中的包装函数中获得相同的上下文?

How get the same context in wrapped function in Python?

在示例中,包装函数 one_func() 没有“看到”Python

中的兄弟函数 another_func()
def wrap_func(call_func):
    call_func()
    print('end')


@wrap_func
def one_func():
    print(123)
    # >>> no such function here
    another_func()


def another_func():
    print(555)


one_func()

实际输出:

$ python test_wrap.py
123
[...]
NameError: name 'another_func' is not defined

如何使包装函数“看到”同一区域中的其他函数?

预计会有以下输出:

$ python test_wrap.py
123
555
end

P.S。是的,我们可以将 another_func() 放在 one_func() 下,但它在我的情况下不起作用。

问题是你的装饰器不是装饰器。它没有返回修饰函数,而是在尚未定义 another_func 时立即调用 one_func

让它成为一个合适的装饰器:

def wrap_func(call_func):
    def wrapper():
        call_func()
        print('end')

    return wrapper