问题:如何检查变量是否存在?
我想检查一个变量是否存在。现在我正在做这样的事情:
try:
myVar
except NameError:
# Do something.
是否有其他方法无一exceptions?
I want to check if a variable exists. Now I’m doing something like this:
try:
myVar
except NameError:
# Do something.
Are there other ways without exceptions?
回答 0
要检查是否存在局部变量:
if 'myVar' in locals():
# myVar exists.
要检查是否存在全局变量:
if 'myVar' in globals():
# myVar exists.
要检查对象是否具有属性:
if hasattr(obj, 'attr_name'):
# obj.attr_name exists.
To check the existence of a local variable:
if 'myVar' in locals():
# myVar exists.
To check the existence of a global variable:
if 'myVar' in globals():
# myVar exists.
To check if an object has an attribute:
if hasattr(obj, 'attr_name'):
# obj.attr_name exists.
回答 1
在使用中那些尚未被定义或组(或明或暗地)变量几乎总是一件坏事任何语言,因为这往往预示着该计划的逻辑还没有被恰当地考虑,并有可能的结果行为无法预测。
如果您需要在Python中执行此操作,以下与您的操作类似的技巧将确保变量在使用前具有一定的价值:
try:
myVar
except NameError:
myVar = None
# Now you're free to use myVar without Python complaining.
但是,我仍然不认为这是个好主意-在我看来,您应该尝试重构代码,以免发生这种情况。
The use of variables that have yet to been defined or set (implicitly or explicitly) is almost always a bad thing in any language, since it often indicates that the logic of the program hasn’t been thought through properly, and is likely to result in unpredictable behaviour.
If you need to do it in Python, the following trick, which is similar to yours, will ensure that a variable has some value before use:
try:
myVar
except NameError:
myVar = None
# Now you're free to use myVar without Python complaining.
However, I’m still not convinced that’s a good idea – in my opinion, you should try to refactor your code so that this situation does not occur.
回答 2
一种简单的方法是一开始就初始化它 myVar = None
然后稍后:
if myVar is not None:
# Do something
A simple way is to initialize it at first saying myVar = None
Then later on:
if myVar is not None:
# Do something
回答 3
使用try / except是测试变量是否存在的最佳方法。但是几乎可以肯定,有一种比设置/测试全局变量更好的方法。
例如,如果您想在第一次调用某个函数时初始化模块级变量,那么最好使用如下代码:
my_variable = None
def InitMyVariable():
global my_variable
if my_variable is None:
my_variable = ...
Using try/except is the best way to test for a variable’s existence. But there’s almost certainly a better way of doing whatever it is you’re doing than setting/testing global variables.
For example, if you want to initialize a module-level variable the first time you call some function, you’re better off with code something like this:
my_variable = None
def InitMyVariable():
global my_variable
if my_variable is None:
my_variable = ...
回答 4
对于对象/模块,您还可以
'var' in dir(obj)
例如,
>>> class Something(object):
... pass
...
>>> c = Something()
>>> c.a = 1
>>> 'a' in dir(c)
True
>>> 'b' in dir(c)
False
for objects/modules, you can also
'var' in dir(obj)
For example,
>>> class Something(object):
... pass
...
>>> c = Something()
>>> c.a = 1
>>> 'a' in dir(c)
True
>>> 'b' in dir(c)
False
回答 5
我将假定该测试将在功能中使用,类似于user97370的答案。我不喜欢这个答案,因为它污染了全局命名空间。解决该问题的一种方法是改用类:
class InitMyVariable(object):
my_variable = None
def __call__(self):
if self.my_variable is None:
self.my_variable = ...
我不喜欢这样,因为它使代码复杂化,并提出了一些问题,例如,是否应该确认Singleton编程模式?幸运的是,Python允许函数在一段时间内拥有属性,这为我们提供了一个简单的解决方案:
def InitMyVariable():
if InitMyVariable.my_variable is None:
InitMyVariable.my_variable = ...
InitMyVariable.my_variable = None
I will assume that the test is going to be used in a function, similar to user97370’s answer. I don’t like that answer because it pollutes the global namespace. One way to fix it is to use a class instead:
class InitMyVariable(object):
my_variable = None
def __call__(self):
if self.my_variable is None:
self.my_variable = ...
I don’t like this, because it complicates the code and opens up questions such as, should this confirm to the Singleton programming pattern? Fortunately, Python has allowed functions to have attributes for a while, which gives us this simple solution:
def InitMyVariable():
if InitMyVariable.my_variable is None:
InitMyVariable.my_variable = ...
InitMyVariable.my_variable = None
回答 6
catch
is called except
in Python. other than that it’s fine for such simple cases. There’s the AttributeError
that can be used to check if an object has an attribute.
回答 7
处理这种情况的一种通常有效的方法是不显式检查变量是否存在,而只是继续将可能不存在的变量的首次用法包装在try / except NameError中:
# Search for entry.
for x in y:
if x == 3:
found = x
# Work with found entry.
try:
print('Found: {0}'.format(found))
except NameError:
print('Not found')
else:
# Handle rest of Found case here
...
A way that often works well for handling this kind of situation is to not explicitly check if the variable exists but just go ahead and wrap the first usage of the possibly non-existing variable in a try/except NameError:
# Search for entry.
for x in y:
if x == 3:
found = x
# Work with found entry.
try:
print('Found: {0}'.format(found))
except NameError:
print('Not found')
else:
# Handle rest of Found case here
...
回答 8
我创建了一个自定义函数。
def exists(var):
var_exists = var in locals() or var in globals()
return var_exists
然后调用如下函数,将其替换variable_name
为要检查的变量:
exists("variable_name")
将返回True
或False
I created a custom function.
def exists(var):
var_exists = var in locals() or var in globals()
return var_exists
Then the call the function like follows replacing variable_name
with the variable you want to check:
exists("variable_name")
Will return True
or False