Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 975
Peter van Arkel Avatar asked Jan 25 '26 10:01

Peter van Arkel


1 Answers

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.

like image 155
mikey Avatar answered Jan 28 '26 00:01

mikey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!