Skip to content

Commit 02c5266

Browse files
committed
Allow to create the unnamed section from scratch.
May fix #123049.
1 parent e2f2dc7 commit 02c5266

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

Lib/configparser.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -694,6 +694,7 @@ def add_section(self, section):
694694

695695
if section in self._sections:
696696
raise DuplicateSectionError(section)
697+
697698
self._sections[section] = self._dict()
698699
self._proxies[section] = SectionProxy(self, section)
699700

@@ -1243,7 +1244,11 @@ def add_section(self, section):
12431244
"""Create a new section in the configuration. Extends
12441245
RawConfigParser.add_section by validating if the section name is
12451246
a string."""
1246-
self._validate_value_types(section=section)
1247+
if section is UNNAMED_SECTION:
1248+
if not self._allow_unnamed_section:
1249+
raise ValueError("Unnamed section not enabled")
1250+
else:
1251+
self._validate_value_types(section=section)
12471252
super().add_section(section)
12481253

12491254
def _read_defaults(self, defaults):

Lib/test/test_configparser.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2161,6 +2161,11 @@ def test_no_section(self):
21612161
self.assertEqual('1', cfg2[configparser.UNNAMED_SECTION]['a'])
21622162
self.assertEqual('2', cfg2[configparser.UNNAMED_SECTION]['b'])
21632163

2164+
def test_add_section(self):
2165+
cfg = configparser.ConfigParser(allow_unnamed_section=True)
2166+
cfg.add_section(configparser.UNNAMED_SECTION)
2167+
cfg.set(configparser.UNNAMED_SECTION, 'a', '1')
2168+
self.assertEqual('1', cfg[configparser.UNNAMED_SECTION]['a'])
21642169

21652170
class MiscTestCase(unittest.TestCase):
21662171
def test__all__(self):

0 commit comments

Comments
 (0)