what is the right way to treat Python argparse.Namespace() as a dictionary?

前端 未结 3 1306
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 10:25

If I want to use the results of argparse.ArgumentParser(), which is a Namespace object, with a method that expects a dictionary or mapping-like obj

相关标签:
3条回答
  • 2020-11-27 10:38

    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.

    0 讨论(0)
  • 2020-11-27 10:43

    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

    0 讨论(0)
  • 2020-11-27 10:55

    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.

    0 讨论(0)
提交回复
热议问题