[英]Simpler way to check if multiple variables exist?
I know a way how to check if one variable exists:我知道一种方法如何检查一个变量是否存在:
try:
my_var
except NameError:
# not exist
I need to check for existence of many variables and make an action only if all of them exist.我需要检查许多变量是否存在,并且只有在所有变量都存在时才采取行动。 Writing a chain of
try..except
or wrapping a few try..except
's one around another looks rather ugly.编写一系列
try..except
或包装一些try..except
的一个看起来相当难看。 Is there any nice way to check many vars?有什么好方法可以检查许多变量吗?
If there is no way around, you can check the return value of dir()
.如果没有办法,您可以检查
dir()
的返回值。 sets
might come in handy. sets
可能会派上用场。
a = 1
b = 2
d = 3
set_vars = {'a', 'b', 'c', 'd'} # declare the variable names to check for
set_vars_exist = set_vars.intersection(set(dir()))
all_vars_exist = set_vars_exist == set_vars
print(all_vars_exist)
# False, because c is missing
Be aware that there might be some pathological edge case (depending on the output of dir()
) where this code fails.请注意,此代码可能会出现一些异常情况(取决于
dir()
的 output )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.