简体   繁体   中英

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. Is there any nice way to check many vars?

If there is no way around, you can check the return value of dir() . sets might come in handy.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM