Skip to content

Commit

Permalink
cpython-main rev=be257c58152e
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Aug 18, 2024
1 parent cafb935 commit 236c1bb
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 10 deletions.
32 changes: 22 additions & 10 deletions Lib/configparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@
"NoOptionError", "InterpolationError", "InterpolationDepthError",
"InterpolationMissingOptionError", "InterpolationSyntaxError",
"ParsingError", "MissingSectionHeaderError",
"MultilineContinuationError",
"MultilineContinuationError", "UnnamedSectionDisabledError",
"ConfigParser", "RawConfigParser",
"Interpolation", "BasicInterpolation", "ExtendedInterpolation",
"SectionProxy", "ConverterMapping",
Expand Down Expand Up @@ -362,6 +362,14 @@ def __init__(self, filename, lineno, line):
self.line = line
self.args = (filename, lineno, line)


class UnnamedSectionDisabledError(Error):
"""Raised when an attempt to use UNNAMED_SECTION is made with the
feature disabled."""
def __init__(self):
Error.__init__(self, "Support for UNNAMED_SECTION is disabled.")


class _UnnamedSection:

def __repr__(self):
Expand Down Expand Up @@ -692,6 +700,10 @@ def add_section(self, section):
if section == self.default_section:
raise ValueError('Invalid section name: %r' % section)

if section is UNNAMED_SECTION:
if not self._allow_unnamed_section:
raise UnnamedSectionDisabledError

if section in self._sections:
raise DuplicateSectionError(section)
self._sections[section] = self._dict()
Expand Down Expand Up @@ -957,7 +969,7 @@ def write(self, fp, space_around_delimiters=True):
self._sections[section].items(), d)

def _write_section(self, fp, section_name, section_items, delimiter, unnamed=False):
"""Write a single section to the specified `fp'."""
"""Write a single section to the specified 'fp'."""
if not unnamed:
fp.write("[{}]\n".format(section_name))
for key, value in section_items:
Expand Down Expand Up @@ -1203,20 +1215,20 @@ def _convert_to_boolean(self, value):
return self.BOOLEAN_STATES[value.lower()]

def _validate_value_types(self, *, section="", option="", value=""):
"""Raises a TypeError for non-string values.
"""Raises a TypeError for illegal non-string values.
The only legal non-string value if we allow valueless
options is None, so we need to check if the value is a
string if:
- we do not allow valueless options, or
- we allow valueless options but the value is not None
Legal non-string values are UNNAMED_SECTION and falsey values if
they are allowed.
For compatibility reasons this method is not used in classic set()
for RawConfigParsers. It is invoked in every case for mapping protocol
access and in ConfigParser.set().
"""
if not isinstance(section, str):
raise TypeError("section names must be strings")
if section is UNNAMED_SECTION:
if not self._allow_unnamed_section:
raise UnnamedSectionDisabledError
elif not isinstance(section, str):
raise TypeError("section names must be strings or UNNAMED_SECTION")
if not isinstance(option, str):
raise TypeError("option keys must be strings")
if not self._allow_no_value or value:
Expand Down
13 changes: 13 additions & 0 deletions Lib/test/test_configparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -2161,6 +2161,19 @@ def test_no_section(self):
self.assertEqual('1', cfg2[configparser.UNNAMED_SECTION]['a'])
self.assertEqual('2', cfg2[configparser.UNNAMED_SECTION]['b'])

def test_add_section(self):
cfg = configparser.ConfigParser(allow_unnamed_section=True)
cfg.add_section(configparser.UNNAMED_SECTION)
cfg.set(configparser.UNNAMED_SECTION, 'a', '1')
self.assertEqual('1', cfg[configparser.UNNAMED_SECTION]['a'])

def test_disabled_error(self):
with self.assertRaises(configparser.MissingSectionHeaderError):
configparser.ConfigParser().read_string("a = 1")

with self.assertRaises(configparser.UnnamedSectionDisabledError):
configparser.ConfigParser().add_section(configparser.UNNAMED_SECTION)


class MiscTestCase(unittest.TestCase):
def test__all__(self):
Expand Down

0 comments on commit 236c1bb

Please sign in to comment.