我试图在实例化后在 configparser.ConfigParser 实例上设置默认值。
在检查实例时,我发现了方法 ConfigParser.setdefault()
:
Help on method setdefault in module collections.abc:
setdefault(key, default=None) method of configparser.ConfigParser instance
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
虽然这根本没有多大帮助,但official documentation甚至没有提到这个public方法。
所以我开始尝试错误:
>>> cp.setdefault('asd', 'foo')
<Section: asd>
>>> cp['asd']
<Section: asd>
>>> cp['asd']['foo']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.6/configparser.py", line 1233, in __getitem__
raise KeyError(key)
KeyError: 'foo'
>>> cp['foo']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.6/configparser.py", line 959, in __getitem__
raise KeyError(key)
KeyError: 'foo'
>>> cp.setdefault('asd', {'foo': 'bar'})
<Section: asd>
>>> cp['asd']
<Section: asd>
>>> cp['asd']['foo']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.6/configparser.py", line 1233, in __getitem__
raise KeyError(key)
KeyError: 'foo'
>>> cp['foo']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.6/configparser.py", line 959, in __getitem__
raise KeyError(key)
KeyError: 'foo'
>>>
但我不知道如何使用默认键 'foo'
和值 'bar'
初始化默认部分 'asd'
>.
所以我的问题是:
ConfigParser.setdefault()
方法的用途是什么?- 如何在
ConfigParser
实例初始化后设置默认值?
更新
经过进一步调查,发现 ConfigParser.setdefault()
继承自 _collections_abc.MutableMapping
。
最佳答案
ConfigParser.setdefault
与设置 ConfigParser 的默认值无关。如果要设置默认值,请使用 DEFAULT
部分,为其他部分提供默认值:
cp['DEFAULT']['key'] = 'value'
或者如果您配置了不同的 default_section
,使用您配置的任何内容。
如 docs 中所述,
configparser objects behave as close to actual dictionaries as possible. The mapping interface is complete and adheres to the MutableMapping ABC. However, there are a few differences that should be taken into account:
[list of differences, none of which involve
setdefault
]
setdefault
是 MutableMapping 指定的操作之一。 cp.setdefault('asd', 'foo')
尝试设置cp['asd'] = 'foo'
如果没有 cp['asd']
的条目,然后返回cp['asd']
.
在 ConfigParser 中,cp['asd']
的条目将是 'asd'
部分,并且设置 cp['asd'] = 'foo'
是不合法的。设置 cp['asd']
是合法的到映射,但您已经有了 cp['asd']
部分,所以你的cp.setdefault('asd', {'foo': 'bar'})
调用也没有执行任何操作。
关于python - ConfigParser.setdefault() 的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51617423/