Search code examples
pythonconcept

weird issue in python: UnboundLocalError: local variable 'y' referenced before assignment


If just got confronted with a weird issue in a program of mine. If simplified my code to the following:

def x(y="test"):
    def xx():
        if False:
            y = "blubb"
        print y
    xx()
    print y

x()

This throws the UnboundLocalError: referenced before assignment Error.

If i fix the code to the following:

def x(y="test"):
    def xx():
        print y
    xx()
    print y

x()

My code works again. I'm on Python 2.7. I've just figured out, that the follow fix work as well and this is how i'm going to fix my software for the moment:

def x(y="test"):
    def xx():
        _y = y
        if False:
            _y = "blubb"
        print _y
    xx()
    print y

x()

Solution

  • Check the LEGB rule in this answer for a general answer.

    In your non-working first example, y is a Local variable, but it is not assigned and that raises an exception. The danger of not raising it would be much larger, as bugs in other cases could pass unnoticed easily (values for variables could be fetch from parent functions unwillingly).

    In your second example, y is not a local variable, so by the LEGB rule the y variable is found in its parent function, and everything works.

    The final example works because you use a local variable _y that it is always assigned.