Determine if variable is defined in Python [duplicate]

混江龙づ霸主 提交于 2019-11-26 06:54:08

问题


Possible Duplicate:
Easy way to check that variable is defined in python?
How do I check if a variable exists in Python?

How do you know whether a variable has been set at a particular place in the code at runtime? This is not always obvious because (1) the variable could be conditionally set, and (2) the variable could be conditionally deleted. I\'m looking for something like defined() in Perl or isset() in PHP or defined? in Ruby.

if condition:
    a = 42

# is \"a\" defined here?

if other_condition:
    del a

# is \"a\" defined here?

回答1:


try:
    thevariable
except NameError:
    print("well, it WASN'T defined after all!")
else:
    print("sure, it was defined.")



回答2:


'a' in vars() or 'a' in globals()

if you want to be pedantic, you can check the builtins too
'a' in vars(__builtins__)




回答3:


I think it's better to avoid the situation. It's cleaner and clearer to write:

a = None
if condition:
    a = 42



回答4:


try:
    a # does a exist in the current namespace
except NameError:
    a = 10 # nope



回答5:


One possible situation where this might be needed:

If you are using finally block to close connections but in the try block, the program exits with sys.exit() before the connection is defined. In this case, the finally block will be called and the connection closing statement will fail since no connection was created.




回答6:


For this particular case it's better to do a = None instead of del a. This will decrement reference count to object a was (if any) assigned to and won't fail when a is not defined. Note, that del statement doesn't call destructor of an object directly, but unbind it from variable. Destructor of object is called when reference count became zero.



来源:https://stackoverflow.com/questions/1592565/determine-if-variable-is-defined-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!