Skip to content Skip to sidebar Skip to footer

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

Solution 1:

You could try something like this:

>>>defined_args = {k:v for k,v in args._get_kwargs() if v isnotNone}>>>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 isnotNone}
{'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.

Solution 2:

I think you can use vars():

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

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

Post a Comment for "Using Argparse Arguments As Keyword Arguments"