diff --git a/Lib/configparser.py b/Lib/configparser.py index b7a0b0b56893c5..7e01d1f53d3c19 100644 --- a/Lib/configparser.py +++ b/Lib/configparser.py @@ -1062,8 +1062,6 @@ def write(self, fp, space_around_delimiters=True): d = f" {self._delimiters[0]} " else: d = self._delimiters[0] - if self._defaults: - self._write_section(fp, self.default_section, self._defaults.items(), d) if self._sections.get(UNNAMED_SECTION): self._write_section( fp, @@ -1072,6 +1070,8 @@ def write(self, fp, space_around_delimiters=True): d, unnamed=True, ) + if self._defaults: + self._write_section(fp, self.default_section, self._defaults.items(), d) for section in self._sections: if section is UNNAMED_SECTION: diff --git a/Lib/test/test_configparser.py b/Lib/test/test_configparser.py index 61b8d1c527d347..9c4c532ecc5c8a 100644 --- a/Lib/test/test_configparser.py +++ b/Lib/test/test_configparser.py @@ -2455,6 +2455,17 @@ def test_add_section(self): cfg.write(output) self.assertEqual(output.getvalue(), 'a = 1\n\n') + def test_write_roundtrip_with_default(self): + US = configparser.UNNAMED_SECTION + cfg = configparser.ConfigParser(allow_unnamed_section=True) + cfg.read_string('key1 = val1\n[DEFAULT]\ndkey = dval\n[sect1]\nkey2 = val2\n') + out = io.StringIO() + cfg.write(out) + cfg2 = configparser.ConfigParser(allow_unnamed_section=True) + cfg2.read_string(out.getvalue()) + self.assertIn('key1', cfg2[US]) + self.assertNotIn('key1', cfg2.defaults()) + def test_disabled_error(self): with self.assertRaises(configparser.MissingSectionHeaderError): configparser.ConfigParser().read_string("a = 1") diff --git a/Misc/NEWS.d/next/Library/2026-07-24-20-00-00.gh-issue-154596.CfgWrt.rst b/Misc/NEWS.d/next/Library/2026-07-24-20-00-00.gh-issue-154596.CfgWrt.rst new file mode 100644 index 00000000000000..79d6a6f7219f1f --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-07-24-20-00-00.gh-issue-154596.CfgWrt.rst @@ -0,0 +1,3 @@ +Fix :meth:`configparser.ConfigParser.write` outputting unnamed-section +items after the ``[DEFAULT]`` header, causing them to be absorbed into +DEFAULT on re-read. Patch by tonghuaroot.