I cannot understand what goes wrong in the following simple example in python 3.6.8:
import functools
def test(cache=False):
def decorator_init(func):
@functools.wraps(func)
def wrapper_init(*args, **kwargs):
print(cache)
#cache = False
return wrapper_init
return decorator_init
@test(cache=False)
def main():
return None
main()
Uncommenting cache = False
will cause this program to fail saying that
Traceback (most recent call last):
File "C:/.../debug.py", line 16, in <module>
main()
File "C:/.../debug.py", line 7, in wrapper_init
print(cache)
UnboundLocalError: local variable 'cache' referenced before assignment
Why does attempting to mutate this variable lead to it being referenced before assignment, but otherwise it's fine to call it in a print statement?