Skip to content

[3.13] gh-127096: Do not recreate unnamed section on every read in ConfigParser (GH-127228) #129593

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 4 additions & 8 deletions Lib/configparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -1093,11 +1093,7 @@ def _handle_continuation_line(self, st, line, fpname):
def _handle_rest(self, st, line, fpname):
# a section header or option header?
if self._allow_unnamed_section and st.cursect is None:
st.sectname = UNNAMED_SECTION
st.cursect = self._dict()
self._sections[st.sectname] = st.cursect
self._proxies[st.sectname] = SectionProxy(self, st.sectname)
st.elements_added.add(st.sectname)
self._handle_header(st, UNNAMED_SECTION, fpname)

st.indent_level = st.cur_indent_level
# is it a section header?
Expand All @@ -1106,10 +1102,10 @@ def _handle_rest(self, st, line, fpname):
if not mo and st.cursect is None:
raise MissingSectionHeaderError(fpname, st.lineno, line)

self._handle_header(st, mo, fpname) if mo else self._handle_option(st, line, fpname)
self._handle_header(st, mo.group('header'), fpname) if mo else self._handle_option(st, line, fpname)

def _handle_header(self, st, mo, fpname):
st.sectname = mo.group('header')
def _handle_header(self, st, sectname, fpname):
st.sectname = sectname
if st.sectname in self._sections:
if self._strict and st.sectname in st.elements_added:
raise DuplicateSectionError(st.sectname, fpname,
Expand Down
9 changes: 9 additions & 0 deletions Lib/test/test_configparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -2161,6 +2161,15 @@ def test_no_section(self):
self.assertEqual('1', cfg2[configparser.UNNAMED_SECTION]['a'])
self.assertEqual('2', cfg2[configparser.UNNAMED_SECTION]['b'])

def test_multiple_configs(self):
cfg = configparser.ConfigParser(allow_unnamed_section=True)
cfg.read_string('a = 1')
cfg.read_string('b = 2')

self.assertEqual([configparser.UNNAMED_SECTION], cfg.sections())
self.assertEqual('1', cfg[configparser.UNNAMED_SECTION]['a'])
self.assertEqual('2', cfg[configparser.UNNAMED_SECTION]['b'])


class MiscTestCase(unittest.TestCase):
def test__all__(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Do not recreate unnamed section on every read in
:class:`configparser.ConfigParser`. Patch by Andrey Efremov.
Loading