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


if got confronted weird issue in program of mine. if simplified code following:

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

this throws unboundlocalerror: referenced before assignment error.

if fix code 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 figured out, follow fix work , how i'm going fix software moment:

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

check legb rule in this answer general answer.

in non-working first example, y local variable, not assigned , raises exception. danger of not raising larger, bugs in other cases pass unnoticed (values variables fetch parent functions unwillingly).

in second example, y not local variable, legb rule y variable found in parent function, , works.

the final example works because use local variable _y assigned.


Comments