Reputation: 64125
I am experiencing by far the weirdest error I've come across right now. My code is simple:
wtf = 5
def update():
print(wtf)
wtf = 1
update()
With the line # wtf = 1
commented out, all works fine, and 5 is printed. However, if I uncomment out # wtf = 1
, before I can even print out wtf
(5), I get an UnboundLocalError: local variable 'wtf' referenced before assignment
. I have no idea WTF is going on here. Why is this happening?
Upvotes: 1
Views: 137
Reputation: 224867
When there’s potential for a variable to be assigned to in a scope, that variable becomes local to that scope. You can prevent that behaviour using global
for global variables, or nonlocal
for any non-local in Python 3:
wtf = 5
def update(dt):
nonlocal wtf
print(wtf)
wtf = 1
Upvotes: 1
Reputation: 6935
When all you have is print(wtf)
in that function, Python assumes that you're just trying to print the global wtf
. If you add in wtf = 1
, then Python is forced to assume you're trying to change a local variable - you can't assign new values to a global variable in a function, unless you use global wtf
at the top. So in that second case, Python assumes that wtf
is a local, which is why the print(wtf)
statement fails - you're now trying to print a local variable before it was assigned, or so Python thinks.
To fix this, add global wtf
as the first line of your update
function.
Upvotes: 2