In Python, how do I check if a variable exists? [duplicate]
If "x" exists, then print "x exists".
开发者_开发问答I ask this because I always get this error:
UnboundLocalError at /settings/
local variable 'avatarlink' referenced before assignment
Why do you need to know? If the code breaks because of this, it's probably because the code is wrong anyway and needs to be fixed.
That said, try checking if 'x' in locals()
or if 'x' in globals()
, as appropriate to where you're expecting it to be.
As they say in Python, "it's better to ask forgiveness than permission". So, just try and access the variable, and catch the error if it doesn't exist.
try:
x
print "x exists"
except UnboundLocalError:
print "x doesn't exist"
However, I would really like to know why you think you need to do this. Usually, you would always set the variable before checking its value.
try:
variable
except NameError:
print "It doesn't Exist!"
else:
print "It exists!"
You may check if x is in globals()
or locals()
.
In python you really shouldn't be using variables which haven't been set. If need be you can set avatarLink to None.
精彩评论