Search code examples
pythonpython-3.xwrapper

How get the same context in wrapped function in Python?


In the example, the wrapped function one_func() does not "see" sibling function another_func() in Python

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()

Actual output:

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

How to make a wrapped function "to see" other functions in the same area?

It's expected to have the following output:

$ python test_wrap.py
123
555
end

P.S. Yes, we may put another_func() under one_func() but it does not work in my case.


Solution

  • The problem is that your decorator isn't a decorator. It's not returning a decorated function, it's instead immediately calling one_func, at a time when another_func hasn't been defined yet.

    Make it a proper decorator:

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