From: Andrey Efremov Date: Mon, 17 Feb 2025 13:24:57 +0000 (+0700) Subject: gh-129678: ConfigParser: do not write an empty unnamed section (GH-129679) X-Git-Tag: v3.14.0a6~386 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=ef8eeca9d8d464cff0e7bc5c428e9b8ba4936962;p=thirdparty%2FPython%2Fcpython.git gh-129678: ConfigParser: do not write an empty unnamed section (GH-129679) Co-authored-by: Petr Viktorin --- diff --git a/Lib/configparser.py b/Lib/configparser.py index 9dc4fa515cfc..9ff52e03c2c4 100644 --- a/Lib/configparser.py +++ b/Lib/configparser.py @@ -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: diff --git a/Lib/test/test_configparser.py b/Lib/test/test_configparser.py index bde805eb741c..c2c82ebe6a87 100644 --- a/Lib/test/test_configparser.py +++ b/Lib/test/test_configparser.py @@ -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) 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 000000000000..5c91a0f99e88 --- /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