matthias
matthias

Reputation: 2181

Using argparse arguments as keyword arguments

Let's say I have an args namespace after parsing my command line with argparse. Now, I want to use this to create some objects like this:

foo = Foo(bar=args.bar)

Unfortunately, I have the restriction that if a keyword argument is set, it must not be None. Now, I need to check if args.bar is set and act accordingly:

if args.bar:
    foo = Foo(bar=args.bar)
else:
    foo = Foo()

This is unwieldy and doesn't scale for more arguments. What I'd like to have, is something like this:

foo = Foo(**args.__dict__)

but this still suffers from my initial problem and additionally doesn't work for keys that are not keyword arguments of the __init__ method. Is there a good way to achieve these things?

Upvotes: 3

Views: 2110

Answers (2)

Dana Spitzer Friedlander
Dana Spitzer Friedlander

Reputation: 1428

I think you can use vars():

args = parser.parse_args()
Foo(**vars(args))

vars([object]) returns the namespace as a dictionary

Upvotes: 2

isedev
isedev

Reputation: 19641

You could try something like this:

>>> defined_args = {k:v for k,v in args._get_kwargs() if v is not None}
>>> foo = Foo(**defined_args)

For example:

>>> import argparse
>>> args = argparse.Namespace(key1=None,key2='value')
>>> {k:v for k,v in args._get_kwargs() if v is not None}
{'key2': 'value'}

Note, however, that _get_kwargs() is not part of the public API so may or may not be available in future releases/versions.

Upvotes: 3

Related Questions