ConfigParser.setdefault() 的用法

Usage of ConfigParser.setdefault()

我正在尝试在 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'

所以我的问题是:

  1. 方法ConfigParser.setdefault()有什么用?
  2. 如何在 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'] 没有条目,则 returns cp['asd'].

在 ConfigParser 中,cp['asd'] 的条目将是一个 'asd' 部分,设置 cp['asd'] = 'foo' 是非法的。将 cp['asd'] 设置为映射是合法的,但是您已经有一个 cp['asd'] 部分,因此您的 cp.setdefault('asd', {'foo': 'bar'}) 调用也没有做任何事情。