0

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?

3
  • You are referencing a variable even before its assignment! Commented Mar 19, 2019 at 11:11
  • 1
    @DirtyBit how come I can access its value in the print() then in the first example? Commented Mar 19, 2019 at 11:14
  • 1
    The presence or absence of msg =, i.e. an assignment to the variable, makes all the difference. Commented Mar 19, 2019 at 11:27

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.