]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-129678: ConfigParser: do not write an empty unnamed section (GH-129679)
authorAndrey Efremov <duxus@yandex.ru>
Mon, 17 Feb 2025 13:24:57 +0000 (20:24 +0700)
committerGitHub <noreply@github.com>
Mon, 17 Feb 2025 13:24:57 +0000 (14:24 +0100)
Co-authored-by: Petr Viktorin <encukou@gmail.com>
Lib/configparser.py
Lib/test/test_configparser.py
Misc/NEWS.d/next/Library/2025-02-05-15-17-31.gh-issue-129678.GIUrmV.rst [new file with mode: 0644]

index 9dc4fa515cfcbea4c1ba894103af616955d3b9cd..9ff52e03c2c4581adaa0ec5b5f1b6eebd16305d7 100644 (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:
index bde805eb741c33d690d9d30f1fe8b068ea55b0fb..c2c82ebe6a87aa265036da7df850b21a4be52bea 100644 (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)
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 (file)
index 0000000..5c91a0f
--- /dev/null
@@ -0,0 +1 @@
+:class:`configparser.ConfigParser`: do not write an empty unnamed section