简体   繁体   中英

Elegant way to check if any of long list of variables is not None, and return the one that isn't?

I have 8 variables being loaded in from environment variables. If any of these are none, I'd like to bail and sys.exit - but I'd also like to alert the user to which variable was missing.

There are a few ways of doing this. Assume the a = os.environ.get('a') code is prewritten, through h

The most verbose way that works is:

if a is None:
    print("A is required")
    sys.exit(1)
if b is None:
    print("B is required")
    sys.exit(1)
if c is None:
    print("C is required")
    sys.exit(1)
...
so on until the check for h

The cleanest way is:

if not any([a,b,c,d,e,f,g,h]):
    print("? is required")
    sys.exit(1)

or even:

if None in [a,b,c,d,e,f,g,h]:
    print("? is required")
    sys.exit(1)

Is it possible to actually get the variable name from one of the more python checks (the latter two) and print it out to the user?

I could get the index of the variable by doing [a,b,c,d,e,f,g,h].index(None) but I'm not sure how to go from the index to the variable name.

Perform the check when you're retrieving the environment variables in the first place:

def needenv(name):
    val = os.environ.get(name)
    if val is None:
        sys.exit('{} is required.'.format(name))
    return val

a = needenv('a')
b = needenv('b')
...

You can loop through the env's:

required_vars = ['a', 'b']
for name in required_vars:
    if not name in os.environ:
        sys.exit('{} is required.'.format(name))

I would read them into a dictionary, you can then use all() to check everything is fine and can also report what is missing (it might be more than one of them).

env_dict[‘a’] = os.environ.get(‘a’) # etc.

if not all(v for k,v in env_dict.items()):
    missing = [k for k,v in env_dict.items() if v is None]

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