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

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

提交回复
热议问题