Karan Sharma
Karan Sharma

Reputation: 495

Argparse Dictionary to Namespace

I use argparse as an argument parser in my python code. What is the best way to parse a dictionary to an argparse object?

For example, My dictionary is:

{
    "activation_dropout": 0.0,
    "activation_fn": "gelu",
    "attention_dropout": 0.0,
    "beam": 1,
}

What I expect is an argparse.Namespace object with attributes activation_dropout, activation_fn, attention_dropout, and beam

I wish there was a method in argparse that takes input as a dictionary and gives out an argparse with the namespace as those variables.

Upvotes: 4

Views: 849

Answers (1)

hpaulj
hpaulj

Reputation: 231385

Just use the ** unpacking:

In [57]: adict={'foo':1, 'bar':'astring', 'baz':[1,2,3]}
In [59]: argparse.Namespace(**adict)
Out[59]: Namespace(bar='astring', baz=[1, 2, 3], foo=1)
In [60]: args = argparse.Namespace(**adict)
In [61]: args
Out[61]: Namespace(bar='astring', baz=[1, 2, 3], foo=1)
In [62]: args.bar
Out[62]: 'astring'

Its docs:

In [63]: argparse.Namespace?
Init signature: argparse.Namespace(**kwargs)
Docstring:     
Simple object for storing attributes.

Implements equality by attribute names and values, and provides a simple string representation.

It's a simple object subclass that assigns its **kwargs to its attributes. And provides a basic display method.

vars is the standard Python method of reversing that:

In [65]: vars(args)
Out[65]: {'foo': 1, 'bar': 'astring', 'baz': [1, 2, 3]}

Internally, parser.parse_args creates an argparse.Namespace() and assigns values with setattr(args, dest, value).

Upvotes: 5

Related Questions