简体   繁体   中英

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

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" (ie 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:

Your assumption was wrong. There is no such thing as a uninitialized variable in Python. Any reference to a "variable" in Python either finds an entry in the namespace of some scope (Local, Enclosing, Global, or Builtin) or it's name lookup error.

It is better to think of Python statements of the form x=y as binding statements rather than assignments . A binding associates a name with an object. The object exists independently of its bindings (instantiated by a literal expression, for example). By contrast, most of the programming languages people are more familiar with have variables ... which have an associated type and location. Python "variables" are entries in a dictionary and the id() returns the the location of the object to which a name is bound. (The fact that this is a memory location is an implementation detail; but the principle is that Python "variable names" are not like the "variables" of more conventional languages).

Here's a bit more on that: https://softwareengineering.stackexchange.com/a/200123/11737

The best way to do accomplish this is simply refrain from using names before binding values thereto. Poking around in locals() or globals() for such things is just poor, ugly, coding practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM