Skip to content

Commit 914c232

Browse files
authored
gh-127096: Do not recreate unnamed section on every read in ConfigParser (#127228)
* Do not recreate unnamed section on every read in ConfigParser * Remove duplicate section creation code
1 parent 5d9b620 commit 914c232

File tree

3 files changed

+15
-8
lines changed

3 files changed

+15
-8
lines changed

Lib/configparser.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1105,11 +1105,7 @@ def _handle_continuation_line(self, st, line, fpname):
11051105
def _handle_rest(self, st, line, fpname):
11061106
# a section header or option header?
11071107
if self._allow_unnamed_section and st.cursect is None:
1108-
st.sectname = UNNAMED_SECTION
1109-
st.cursect = self._dict()
1110-
self._sections[st.sectname] = st.cursect
1111-
self._proxies[st.sectname] = SectionProxy(self, st.sectname)
1112-
st.elements_added.add(st.sectname)
1108+
self._handle_header(st, UNNAMED_SECTION, fpname)
11131109

11141110
st.indent_level = st.cur_indent_level
11151111
# is it a section header?
@@ -1118,10 +1114,10 @@ def _handle_rest(self, st, line, fpname):
11181114
if not mo and st.cursect is None:
11191115
raise MissingSectionHeaderError(fpname, st.lineno, line)
11201116

1121-
self._handle_header(st, mo, fpname) if mo else self._handle_option(st, line, fpname)
1117+
self._handle_header(st, mo.group('header'), fpname) if mo else self._handle_option(st, line, fpname)
11221118

1123-
def _handle_header(self, st, mo, fpname):
1124-
st.sectname = mo.group('header')
1119+
def _handle_header(self, st, sectname, fpname):
1120+
st.sectname = sectname
11251121
if st.sectname in self._sections:
11261122
if self._strict and st.sectname in st.elements_added:
11271123
raise DuplicateSectionError(st.sectname, fpname,

Lib/test/test_configparser.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2174,6 +2174,15 @@ def test_disabled_error(self):
21742174
with self.assertRaises(configparser.UnnamedSectionDisabledError):
21752175
configparser.ConfigParser().add_section(configparser.UNNAMED_SECTION)
21762176

2177+
def test_multiple_configs(self):
2178+
cfg = configparser.ConfigParser(allow_unnamed_section=True)
2179+
cfg.read_string('a = 1')
2180+
cfg.read_string('b = 2')
2181+
2182+
self.assertEqual([configparser.UNNAMED_SECTION], cfg.sections())
2183+
self.assertEqual('1', cfg[configparser.UNNAMED_SECTION]['a'])
2184+
self.assertEqual('2', cfg[configparser.UNNAMED_SECTION]['b'])
2185+
21772186

21782187
class MiscTestCase(unittest.TestCase):
21792188
def test__all__(self):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Do not recreate unnamed section on every read in
2+
:class:`configparser.ConfigParser`. Patch by Andrey Efremov.

0 commit comments

Comments
 (0)