I am trying to set default values on an instance of configparser.ConfigParser
after its instantiation.
While inspecting the instance I found the method 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
While this is not very helpful at all, the official documentation does not even mention this public method.
So I started just to try-and-error:
>>> 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'
>>>
But I could not figure out how to initialize a default section 'asd'
with a default key 'foo'
with value 'bar'
.
So my questions are:
What is the methodConfigParser.setdefault()
for?- How can I set defaults on my
ConfigParser
's instance after its initialization?
Update
After some further investigation it turned out that ConfigParser.setdefault()
is inherited from _collections_abc.MutableMapping
.