Skip to content

Commit 4aef138

Browse files
authored
gh-136282: Configparser: create unnamed sections via mapping protocol access (GH-136313)
1 parent 610aabf commit 4aef138

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

Lib/configparser.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -794,7 +794,8 @@ def read_dict(self, dictionary, source='<dict>'):
794794
"""
795795
elements_added = set()
796796
for section, keys in dictionary.items():
797-
section = str(section)
797+
if section is not UNNAMED_SECTION:
798+
section = str(section)
798799
try:
799800
self.add_section(section)
800801
except (DuplicateSectionError, ValueError):

Lib/test/test_configparser.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2215,6 +2215,16 @@ def test_add_section(self):
22152215
cfg.add_section(configparser.UNNAMED_SECTION)
22162216
cfg.set(configparser.UNNAMED_SECTION, 'a', '1')
22172217
self.assertEqual('1', cfg[configparser.UNNAMED_SECTION]['a'])
2218+
output = io.StringIO()
2219+
cfg.write(output)
2220+
self.assertEqual(output.getvalue(), 'a = 1\n\n')
2221+
2222+
cfg = configparser.ConfigParser(allow_unnamed_section=True)
2223+
cfg[configparser.UNNAMED_SECTION] = {'a': '1'}
2224+
self.assertEqual('1', cfg[configparser.UNNAMED_SECTION]['a'])
2225+
output = io.StringIO()
2226+
cfg.write(output)
2227+
self.assertEqual(output.getvalue(), 'a = 1\n\n')
22182228

22192229
def test_disabled_error(self):
22202230
with self.assertRaises(configparser.MissingSectionHeaderError):
@@ -2223,6 +2233,9 @@ def test_disabled_error(self):
22232233
with self.assertRaises(configparser.UnnamedSectionDisabledError):
22242234
configparser.ConfigParser().add_section(configparser.UNNAMED_SECTION)
22252235

2236+
with self.assertRaises(configparser.UnnamedSectionDisabledError):
2237+
configparser.ConfigParser()[configparser.UNNAMED_SECTION] = {'a': '1'}
2238+
22262239
def test_multiple_configs(self):
22272240
cfg = configparser.ConfigParser(allow_unnamed_section=True)
22282241
cfg.read_string('a = 1')
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Add support for :const:`~configparser.UNNAMED_SECTION` when creating a
2+
section via the mapping protocol access

0 commit comments

Comments
 (0)