开发者

In Python, how do I check if a variable exists? [duplicate]

开发者 https://www.devze.com 2023-01-29 00:38 出处:网络
This question already has answers here: How do I check if a variable exists? (14 answers) Closed 9 years ago.
This question already has answers here: How do I check if a variable exists? (14 answers) Closed 9 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号