diff --git a/Lib/configparser.py b/Lib/configparser.py index 4344a9e8baca44..bfcb772beb281d 100644 --- a/Lib/configparser.py +++ b/Lib/configparser.py @@ -1112,7 +1112,7 @@ def _handle_header(self, st, mo, fpname): st.sectname = mo.group('header') if st.sectname in self._sections: if self._strict and st.sectname in st.elements_added: - raise DuplicateSectionError(st.sectname, fpname, + self._handle_duplicate_section(st.sectname, fpname, st.lineno) st.cursect = self._sections[st.sectname] st.elements_added.add(st.sectname) @@ -1126,6 +1126,10 @@ def _handle_header(self, st, mo, fpname): # So sections can't start with a continuation line st.optname = None + def _handle_duplicate_section(self, sectname, fpname, lineno): + """Handle duplicate section definition. Override for custom behavior.""" + raise DuplicateSectionError(sectname, fpname, lineno) + def _handle_option(self, st, line, fpname): # an option line? st.indent_level = st.cur_indent_level @@ -1145,7 +1149,7 @@ def _handle_option(self, st, line, fpname): st.optname = self.optionxform(st.optname.rstrip()) if (self._strict and (st.sectname, st.optname) in st.elements_added): - raise DuplicateOptionError(st.sectname, st.optname, + self._handle_duplicate_option(st.sectname, st.optname, fpname, st.lineno) st.elements_added.add((st.sectname, st.optname)) # This check is fine because the OPTCRE cannot @@ -1157,6 +1161,10 @@ def _handle_option(self, st, line, fpname): # valueless option handling st.cursect[st.optname] = None + def _handle_duplicate_option(self, sectname, optname, fpname, lineno): + """Handle duplicate option definition. Override for custom behavior.""" + raise DuplicateOptionError(sectname, optname, fpname, lineno) + def _join_multiline_values(self): defaults = self.default_section, self._defaults all_sections = itertools.chain((defaults,), diff --git a/Misc/NEWS.d/next/Library/2023-07-29-15-26-24.gh-issue-107428.TPmUOE.rst b/Misc/NEWS.d/next/Library/2023-07-29-15-26-24.gh-issue-107428.TPmUOE.rst new file mode 100644 index 00000000000000..cd9740f96168c2 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-07-29-15-26-24.gh-issue-107428.TPmUOE.rst @@ -0,0 +1 @@ +Added overridable methods for handling duplicate sections and options in ConfigParser.