将 Python argparse.Namespace() 视为字典的正确方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16878315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:55:09  来源:igfitidea点击:

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

pythondictionaryduck-typing

提问by Jason S

If I want to use the results of argparse.ArgumentParser(), which is a Namespaceobject, with a method that expects a dictionary or mapping-like object (see collections.Mapping), what is the right way to do it?

如果我想将 的结果(argparse.ArgumentParser()它是一个Namespace对象)与一个需要字典或类似映射的对象的方法一起使用(请参阅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 proper to "reach into" an object and use its __dict__property?

“进入”一个对象并使用它的__dict__属性是否合适?

I would think the answer is no: __dict__smells like a convention for implementation, but not for an interface, the way __getattribute__or __setattr__or __contains__seem to be.

我认为答案是否定的:__dict__闻起来像执行公约,而不是一个接口,方式__getattribute____setattr____contains__似乎是。

采纳答案by Raymond Hettinger

You can access the namespace's dictionary with vars():

您可以使用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.

是的,可以访问 __dict__ 属性。它是一种定义明确、经过测试且有保证的行为。

回答by msw

Is it proper to "reach into" an object and use its dictproperty?

“进入”一个对象并使用它的dict属性是否合适?

In general, I would say "no". However Namespacehas struck me as over-engineered, possibly from when classes couldn't inherit from built-in types.

一般来说,我会说“不”。然而Namespace,我觉得过度设计,可能是因为类无法从内置类型继承。

On the other hand, Namespacedoes 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.

另一方面,Namespaceargparse 确实提出了一种面向任务的方法,我想不出有什么情况需要抓住__dict__,但我的想象力的极限和你的不一样。

回答by Eugene Yarmash

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

如果您更喜欢类似 dict 的属性视图,您可以使用标准的 Python 习惯用法vars()

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> args = parser.parse_args(['--foo', 'BAR'])
>>> vars(args)
{'foo': 'BAR'}

— Python 标准库,16.4.4.6。命名空间对象