简体   繁体   English

检查是否存在多个变量的更简单方法?

[英]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.

相关问题 有没有更简单的方法来从python列表中设置多个变量? - Is there a simpler way to set multiple variables from a list in python? 检查python中是否存在多个变量 - Check whether multiple variables exist in python 创建单独变量字典的更简单方法? - Simpler way to create dictionary of separate variables? 检查网格对角线的更简单方法是什么? - What is a simpler way to check for diagonals on a grid? 有没有更好,更简单的方法来下载多个文件? - Is there a better, simpler way to download multiple files? 检查 if 语句中的多个条件的更简单方法 python - simpler way of checking multiple conditions in if statements python 有没有更简单的方法将变量从外部类传递到内部类? - Is there a simpler way to pass variables from the outer class to an inner class? 有没有更简单的方法来检查列表的长度并输出正确的if语句? - Is there a simpler way check the length of a list and output the correct if statement? 检查两个字符串是否在python中的第三个字符串中的更简单方法 - simpler way to check if two different strings are in a third string in python 如何在一个类中搜索多个变量并打印另一个变量? 有可能使它更简单吗? - How to search multiple variables in a class and print another? Is It possible to make this simpler?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM