Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python | if variable: | UnboundLocalError: local variable 'variable' referenced before assignment

Tags:

python

I am trying to use an if statement to check whether a variable has been assigned and is not None.

# Code that may or may not assign value to 'variable'

if variable: 
    do things

This throws an error at the line with the if statement: "UnboundLocalError: local variable 'variable' referenced before assignment".

I thought if the variable wasn't assigned it would just be interpreted as False?

I've tried if variable in locals(): to no avail.

What's going on? What can I do to achieve the result I'm looking for?

Thanks

like image 469
ChootsMagoots Avatar asked Dec 24 '22 10:12

ChootsMagoots


2 Answers

It's better to simply initialize x to None at the beginning and test for None (as in Ned's answer).


What's going on is that whenever you reference a variable on a "load" (i.e. rvalue), Python looks it up and requires it to exist.

If your variable is named x, the following throws:

if x in locals(): ...

And is not what you wanted, since it would have checked if the value that the variable holds is in locals(). Not whether the name x is there.

But you can do

if 'x' in locals(): ...
like image 123
Elazar Avatar answered Dec 25 '22 23:12

Elazar


At the beginning of the function initialize the variable to None. Then later you can check it with:

if x is not None:
like image 39
Ned Batchelder Avatar answered Dec 25 '22 23:12

Ned Batchelder