https://github.com/python/cpython/commit/ef8eeca9d8d464cff0e7bc5c428e9b8ba4936962 commit: ef8eeca9d8d464cff0e7bc5c428e9b8ba4936962 branch: main author: Andrey Efremov <du...@yandex.ru> committer: encukou <encu...@gmail.com> date: 2025-02-17T14:24:57+01:00 summary:
gh-129678: ConfigParser: do not write an empty unnamed section (GH-129679) Co-authored-by: Petr Viktorin <encu...@gmail.com> files: A Misc/NEWS.d/next/Library/2025-02-05-15-17-31.gh-issue-129678.GIUrmV.rst M Lib/configparser.py M Lib/test/test_configparser.py diff --git a/Lib/configparser.py b/Lib/configparser.py index 9dc4fa515cfcbe..9ff52e03c2c458 100644 --- a/Lib/configparser.py +++ b/Lib/configparser.py @@ -959,7 +959,7 @@ def write(self, fp, space_around_delimiters=True): 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: diff --git a/Lib/test/test_configparser.py b/Lib/test/test_configparser.py index bde805eb741c33..c2c82ebe6a87aa 100644 --- a/Lib/test/test_configparser.py +++ b/Lib/test/test_configparser.py @@ -2161,6 +2161,14 @@ def test_no_section(self): 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) diff --git a/Misc/NEWS.d/next/Library/2025-02-05-15-17-31.gh-issue-129678.GIUrmV.rst b/Misc/NEWS.d/next/Library/2025-02-05-15-17-31.gh-issue-129678.GIUrmV.rst new file mode 100644 index 00000000000000..5c91a0f99e88bd --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-02-05-15-17-31.gh-issue-129678.GIUrmV.rst @@ -0,0 +1 @@ +:class:`configparser.ConfigParser`: do not write an empty unnamed section _______________________________________________ Python-checkins mailing list -- python-checkins@python.org To unsubscribe send an email to python-checkins-le...@python.org https://mail.python.org/mailman3/lists/python-checkins.python.org/ Member address: arch...@mail-archive.com