Coder Perfect

How should argparse.Namespace() be treated as a dictionary in Python?

Problem

If I want to use the argparse results. What is the correct approach to use ArgumentParser(), a Namespace object, with a method that requires a dictionary or mapping-like object (see collections.Mapping)?

C:\>python
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> args.baz = 'yippee'
>>> args['baz']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'Namespace' object has no attribute '__getitem__'
>>> dir(args)
['__class__', '__contains__', '__delattr__', '__dict__', '__doc__', '__eq__', '_
_format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__
', '__str__', '__subclasshook__', '__weakref__', '_get_args', '_get_kwargs', 'ba
r', 'baz', 'foo']

Is it acceptable to use an object’s __dict__ property by “reaching into” it?

No, I believe the answer is no: __dict__ smells like an implementation convention, not an interface, like __getattribute__, __setattr__, or __contains__.

Asked by Jason S

Solution #1

vars() gives you access to the namespace’s dictionary:

>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> d = vars(args)
>>> d
{'foo': 1, 'bar': [1, 2, 3]}

If you like, you can change the dictionary directly:

>>> d['baz'] = 'store me'
>>> args.baz
'store me'

Yes, accessing the __dict__ attribute is permitted. It’s a behavior that’s been well-defined, tested, and guaranteed.

Answered by Raymond Hettinger

Solution #2

‘Right from the horse’s mouth,’ says the horse.

Answered by Eugene Yarmash

Solution #3

I would say “no” in general. Namespace, on the other hand, struck me as over-engineered, perhaps because classes couldn’t inherit from built-in types at the time.

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.

Answered by msw

Solution #4

Note that if you’re trying to treat args as a dict to find out if it has an attribute, you can just do the following instead:

if hasattr(args, 'someProperty'):
    a.someProperty

further information on hasattr, as well as a similar response to another question

You may also acquire the value by using the getattr method, which is similar:

value = getattr(args, 'someProperty')

Answered by Brad Parks

Post is based on https://stackoverflow.com/questions/16878315/what-is-the-right-way-to-treat-python-argparse-namespace-as-a-dictionary