Checking if variable exists in Namespace

Question:

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.

Asked By: Peter van Arkel

||

Answers:

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’

Answered By: Peter van Arkel

Use vars() to convert your namespace to a dictionary, then use dict.get('your key') which will return your object if it exists, or a None when it doesn’t.

Example

my_args.py

import argparse


_parser = argparse.ArgumentParser("A description of your program")

_parser.add_argument("--some-arg", help="foo", action="store_true")
_parser.add_argument("--another-one", type=str)

your_args_dict = vars(_parser.parse_args())

print(your_args_dict.get('some_arg'))
print(your_args_dict.get('another_one'))
print(your_args_dict.get('foo_bar'))

command line

$ python3 my_args.py --some-arg --another-one test

True
test
None

Answered By: Joshua Schlichting

You can use hasattr(ns, "battery") (assume ns = Namespace(battery=False, cache=True, health=False, hotspare=False)).

Much cleaner than vars(ns).get("battery") I would think.

Answered By: mikey

Answering the title (not the OP detailed question), to check that variable a is defined in the ns namespace:

'a' in vars(ns)
Answered By: Axel Bregnsbo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.