]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-136282: Configparser: create unnamed sections via mapping protocol access (GH...
authorRogdham <3994389+Rogdham@users.noreply.github.com>
Fri, 19 Dec 2025 12:44:03 +0000 (13:44 +0100)
committerGitHub <noreply@github.com>
Fri, 19 Dec 2025 12:44:03 +0000 (13:44 +0100)
Lib/configparser.py
Lib/test/test_configparser.py
Misc/NEWS.d/next/Library/2025-07-05-08-30-07.gh-issue-136282.K3JKyD.rst [new file with mode: 0644]

index 18af1eadaad1110bee819d2c24199a3626c63245..d435a5c2fe0da241a76e5e06ccf8336e894bc314 100644 (file)
@@ -794,7 +794,8 @@ class RawConfigParser(MutableMapping):
         """
         elements_added = set()
         for section, keys in dictionary.items():
-            section = str(section)
+            if section is not UNNAMED_SECTION:
+                section = str(section)
             try:
                 self.add_section(section)
             except (DuplicateSectionError, ValueError):
index e7364e18742c16a30a6cfaa5104e1a60753b8b2a..1bfb53ccbb13984dae3bacc655e86382caadf7a1 100644 (file)
@@ -2215,6 +2215,16 @@ class SectionlessTestCase(unittest.TestCase):
         cfg.add_section(configparser.UNNAMED_SECTION)
         cfg.set(configparser.UNNAMED_SECTION, 'a', '1')
         self.assertEqual('1', cfg[configparser.UNNAMED_SECTION]['a'])
+        output = io.StringIO()
+        cfg.write(output)
+        self.assertEqual(output.getvalue(), 'a = 1\n\n')
+
+        cfg = configparser.ConfigParser(allow_unnamed_section=True)
+        cfg[configparser.UNNAMED_SECTION] = {'a': '1'}
+        self.assertEqual('1', cfg[configparser.UNNAMED_SECTION]['a'])
+        output = io.StringIO()
+        cfg.write(output)
+        self.assertEqual(output.getvalue(), 'a = 1\n\n')
 
     def test_disabled_error(self):
         with self.assertRaises(configparser.MissingSectionHeaderError):
@@ -2223,6 +2233,9 @@ class SectionlessTestCase(unittest.TestCase):
         with self.assertRaises(configparser.UnnamedSectionDisabledError):
             configparser.ConfigParser().add_section(configparser.UNNAMED_SECTION)
 
+        with self.assertRaises(configparser.UnnamedSectionDisabledError):
+            configparser.ConfigParser()[configparser.UNNAMED_SECTION] = {'a': '1'}
+
     def test_multiple_configs(self):
         cfg = configparser.ConfigParser(allow_unnamed_section=True)
         cfg.read_string('a = 1')
diff --git a/Misc/NEWS.d/next/Library/2025-07-05-08-30-07.gh-issue-136282.K3JKyD.rst b/Misc/NEWS.d/next/Library/2025-07-05-08-30-07.gh-issue-136282.K3JKyD.rst
new file mode 100644 (file)
index 0000000..b5589b4
--- /dev/null
@@ -0,0 +1,2 @@
+Add support for :const:`~configparser.UNNAMED_SECTION` when creating a
+section via the mapping protocol access