What is the right way to treat argparse.Namespace() as a dictionary?
You can access the namespace's dictionary with vars():
>>> import argparse>>> args = argparse.Namespace()>>> args.foo = 1>>> args.bar = [1,2,3]>>> d = vars(args)>>> d{'foo': 1, 'bar': [1, 2, 3]}
You can modify the dictionary directly if you wish:
>>> d['baz'] = 'store me'>>> args.baz'store me'
Yes, it is okay to access the __dict__ attribute. It is a well-defined, tested, and guaranteed behavior.
Straight from the horse's mouth:
If you prefer to have dict-like view of the attributes, you can use the standard Python idiom,
vars()
:
>>> parser = argparse.ArgumentParser()>>> parser.add_argument('--foo')>>> args = parser.parse_args(['--foo', 'BAR'])>>> vars(args){'foo': 'BAR'}
— The Python Standard Library, 16.4.4.6. The Namespace object
Is it proper to "reach into" an object and use its dict property?
In general, I would say "no". However Namespace
has struck me as over-engineered, possibly from when classes couldn't inherit from built-in types.
On the other hand, Namespace
does present a task-oriented approach to argparse, and I can't think of a situation that would call for grabbing the __dict__
, but the limits of my imagination are not the same as yours.