4

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.

Alex
  • 6,610
  • 3
  • 20
  • 38
Karan Sharma
  • 475
  • 1
  • 5
  • 16
  • Does this answer your question? [Python: load variables in a dict into namespace](https://stackoverflow.com/questions/2597278/python-load-variables-in-a-dict-into-namespace) – Tomerikoo Mar 01 '21 at 12:23
  • @Tomerikoo, an `argparse.Namespace` isn't a module's `namespace` – hpaulj Mar 01 '21 at 14:04
  • @hpaulj don't know about that, but the second answer there is identical to yours and the accepted gives an alternative way... – Tomerikoo Mar 01 '21 at 14:06

1 Answers1

5

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).

hpaulj
  • 221,503
  • 14
  • 230
  • 353