Search code examples
pythonnamespacesargparse

Checking if variable exists in Namespace


I'm trying to use the output of my argparse (simple argparse with just 4 positional arguments that each kick of a function depending on the variable that is set to True)

Namespace(battery=False, cache=True, health=False, hotspare=False)

At the moment I'm trying to figure out how to best ask python to see when one of those variables is set to True; without having to hardcode like I do now:

if args.battery is True:
    do_something()
elif args.cache is True:
    do_something_else()
etc ...

I'd rather just use one command to check if a variable exists within the namespace and if it's set to True; but I can't for the life of me figure out how to do this in an efficient manner.


Solution

  • If solved my problem with a list comprehension (after using the tip to use vars() ) :

    l = [ k for (k,v) in args.items() if v ]
    

    l is a list of keys in the dict that have a value of 'True'