本文翻译自:Determine if variable is defined in Python [duplicate]
Possible Duplicate: 可能重复:
Easy way to check that variable is defined in python? 在python中定义检查变量的简单方法?
How do I check if a variable exists in Python? 如何检查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. 这并不总是显而易见的,因为(1)变量可以有条件地设置,(2)变量可以有条件地删除。 I'm looking for something like defined()
in Perl or isset()
in PHP or defined?
我正在寻找像Perl中的defined()
或PHP中的isset()
或defined?
in Ruby. 在Ruby中。
if condition:
a = 42
# is "a" defined here?
if other_condition:
del a
# is "a" defined here?
#1楼
参考:https://stackoom.com/question/6gIX/确定变量是否在Python中定义-重复
#2楼
try:
a # does a exist in the current namespace
except NameError:
a = 10 # nope
#3楼
try:
thevariable
except NameError:
print("well, it WASN'T defined after all!")
else:
print("sure, it was defined.")
#4楼
'a' in vars() or 'a' in globals()
如果你想变得迂腐,你也可以查看内置的'a' in vars(__builtins__)
#5楼
I think it's better to avoid the situation. 我认为最好避免这种情况。 It's cleaner and clearer to write: 写起来更清晰,更清晰:
a = None
if condition:
a = 42
#6楼
For this particular case it's better to do a = None
instead of del a
. 对于这种特殊情况,最好做a = None
而不是del a
。 This will decrement reference count to object a
was (if any) assigned to and won't fail when a
is not defined. 这将减少对象a
引用计数(如果有的话),并且在未定义a
时将不会失败。 Note, that del
statement doesn't call destructor of an object directly, but unbind it from variable. 注意, del
语句不直接调用对象的析构函数,而是从变量中解除绑定。 Destructor of object is called when reference count became zero. 当引用计数变为零时,将调用对象的析构函数。