I have the following piece of code, it works and gives the correct output:
def msg_before(msg=None):
def actual_decorator(func):
def wrapper(*args, **kwargs):
print(msg if msg is not None else "was none") # original
result = func(*args, **kwargs)
return result
return wrapper
return actual_decorator
@msg_before("this comes before")
def test_func():
print("test")
if __name__ == "__main__":
test_func()
output:
this comes before test
But when I change the wrapper
function like this:
def msg_before(msg=None):
def actual_decorator(func):
def wrapper(*args, **kwargs):
msg = msg if msg is not None else "was none" # changed
print(msg) # changed
result = func(*args, **kwargs)
return result
return wrapper
return actual_decorator
I get the following error:
Traceback (most recent call last): File "C:/Users/ruohola/Desktop/test.py", line 33, in <module> test_func() File "C:/Users/ruohola/Desktop/test.py", line 19, in wrapper msg = msg if msg is not None else "was none" # changed UnboundLocalError: local variable 'msg' referenced before assignment
To me both of the codes seem identical, and I just don't understand where the error comes from and why it doesn't occur in the first code?