gh-129678: ConfigParser: do not write an empty unnamed section (GH-129679)

Co-authored-by: Petr Viktorin <encukou@gmail.com>
This commit is contained in:
Andrey Efremov 2025-02-17 20:24:57 +07:00 committed by GitHub
parent b9d2ee687c
commit ef8eeca9d8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 10 additions and 1 deletions

View file

@ -959,7 +959,7 @@ class RawConfigParser(MutableMapping):
if self._defaults:
self._write_section(fp, self.default_section,
self._defaults.items(), d)
if UNNAMED_SECTION in self._sections:
if UNNAMED_SECTION in self._sections and self._sections[UNNAMED_SECTION]:
self._write_section(fp, UNNAMED_SECTION, self._sections[UNNAMED_SECTION].items(), d, unnamed=True)
for section in self._sections:

View file

@ -2161,6 +2161,14 @@ class SectionlessTestCase(unittest.TestCase):
self.assertEqual('1', cfg2[configparser.UNNAMED_SECTION]['a'])
self.assertEqual('2', cfg2[configparser.UNNAMED_SECTION]['b'])
def test_empty_unnamed_section(self):
cfg = configparser.ConfigParser(allow_unnamed_section=True)
cfg.add_section(configparser.UNNAMED_SECTION)
cfg.add_section('section')
output = io.StringIO()
cfg.write(output)
self.assertEqual(output.getvalue(), '[section]\n\n')
def test_add_section(self):
cfg = configparser.ConfigParser(allow_unnamed_section=True)
cfg.add_section(configparser.UNNAMED_SECTION)

View file

@ -0,0 +1 @@
:class:`configparser.ConfigParser`: do not write an empty unnamed section