Checking if variable exists in Namespace
Asked Answered
U

4

12

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.

Udele answered 3/6, 2015 at 10:40 Comment(1)
argparse uses getattr(namespace, dest) to check for values. vars(args) creates a dictionary. You could gets keys and values from that.Glinys
U
3

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'

Udele answered 3/6, 2015 at 13:47 Comment(0)
S
8

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.

Stealer answered 21/5, 2022 at 16:24 Comment(0)
I
4

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

'a' in vars(ns)
Isaiah answered 9/11, 2022 at 9:8 Comment(0)
U
3

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'

Udele answered 3/6, 2015 at 13:47 Comment(0)
B
3

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

Barina answered 16/6, 2021 at 20:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.