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
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(): ...
At the beginning of the function initialize the variable to None. Then later you can check it with:
if x is not None:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With