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

前端 未结 3 1330
伪装坚强ぢ
伪装坚强ぢ 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: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.

提交回复
热议问题