GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — gh-66449: Add support to unnamed sections in ConfigParser by pslacerda · Pull Request #2735 · python/cpython

gh-66449: Add support to unnamed sections in ConfigParser #2735

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.

Sign up for GitHub

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

Closed
pslacerda wants to merge 9 commits into python:main from pslacerda:fix-issue-issue22253

Uh oh!

There was an error while loading. Please reload this page.

Closed

gh-66449: Add support to unnamed sections in ConfigParser #2735

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
9 commits
Select commit Hold shift + click to select a range
10a5a06
Introducing UNNAMED_SECTION
pslacerda1 Sep 21, 2022
72be2b1
Accepting changes
pslacerda1 Sep 22, 2022
8b7764f
Accepting changes
pslacerda1 Sep 23, 2022
7a05656
Write DEFAULT section before unnamed
pslacerda1 Oct 3, 2022
d7b6281
Turn unnamed section a default section
pslacerda1 Oct 5, 2022
1e0ceb1
Minor fix
pslacerda1 Oct 5, 2022
394b83f
Merge branch 'main' into fix-issue-issue22253
arhadthedev Apr 9, 2023
fa3f10b
Merge branch 'main' into fix-issue-issue22253
arhadthedev May 11, 2023
fdb7081
Update Lib/configparser.py
pslacerda Mar 29, 2024
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

35 changes: 31 additions & 4 deletions 35 Lib/configparser.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
delimiters=('=', ':'), comment_prefixes=('#', ';'),
inline_comment_prefixes=None, strict=True,
empty_lines_in_values=True, default_section='DEFAULT',
interpolation=<unset>, converters=<unset>):
interpolation=<unset>, converters=<unset>,
allow_unnamed_section=False):
Comment thread

@vadmium vadmium Mar 24, 2024

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

allow_unnamed_section not implemented

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@pslacerda pslacerda Mar 26, 2024

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems ok.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

Create the parser. When `defaults` is given, it is initialized into the
dictionary or intrinsic defaults. The keys must be strings, the values
Expand Down Expand Up @@ -68,6 +69,12 @@
converter gets its corresponding get*() method on the parser object and
section proxies.

When `allow_unnamed_section` is True (default: False), options
without section are accepted: the section for this is
Comment thread

@vadmium vadmium Mar 24, 2024

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

options without a section?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
``configparser.UNNAMED_SECTION``. In the file, they are placed before
Comment thread

@vadmium vadmium Mar 24, 2024

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

configparser.TOP_LEVEL?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
the first explicit section header. This also allows reading and writing
files that don't contain any explicit section headers.

sections()
Return all the configuration section names, sans DEFAULT.

Expand Down Expand Up @@ -156,7 +163,7 @@
"ConfigParser", "RawConfigParser",
"Interpolation", "BasicInterpolation", "ExtendedInterpolation",
"LegacyInterpolation", "SectionProxy", "ConverterMapping",
"DEFAULTSECT", "MAX_INTERPOLATION_DEPTH")
"DEFAULTSECT", "MAX_INTERPOLATION_DEPTH", "TOP_LEVEL")

_default_dict = dict
DEFAULTSECT = "DEFAULT"
Expand Down Expand Up @@ -323,6 +330,20 @@ def __init__(self, filename, lineno, line):
self.args = (filename, lineno, line)


class _UnnamedSection:

def __repr__(self):
return "<TOP_LEVEL>"

def __eq__(self, other):
return repr(self) == repr(other)
Comment thread

@vadmium vadmium Mar 24, 2024

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did __eq__ get implemented? It makes more sense to me to keep the default inherited implementation. Doesn’t the class only get instantiated once anyway?

Won’t this make a valid section headed [<TOP_LEVEL>] match the headerless section in some cases?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

def __hash__(self):
return hash(repr(self))

TOP_LEVEL = _UnnamedSection()


# Used in parser getters to indicate the default behaviour when a specific
# option is not found it to raise an exception. Created to enable `None` as
# a valid fallback value.
Expand Down Expand Up @@ -902,7 +923,8 @@ def write(self, fp, space_around_delimiters=True):

def _write_section(self, fp, section_name, section_items, delimiter):
"""Write a single section to the specified `fp`."""
fp.write("[{}]\n".format(section_name))
if section_name is not TOP_LEVEL:
fp.write(f"[{section_name}]\n")
for key, value in section_items:
value = self._interpolation.before_write(self, section_name, key,
value)
Expand Down Expand Up @@ -1038,6 +1060,10 @@ def _read(self, fp, fpname):
cursect[optname].append(value)
# a section header or option header?
else:
if self.default_section is TOP_LEVEL and cursect is None:
sectname = TOP_LEVEL
cursect = self._defaults

Comment thread
pslacerda marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

indent_level = cur_indent_level
# is it a section header?
mo = self.SECTCRE.match(value)
Expand All @@ -1058,7 +1084,7 @@ def _read(self, fp, fpname):
elements_added.add(sectname)
# So sections can't start with a continuation line
optname = None
# no section header in the file?
# no section header?
elif cursect is None:
raise MissingSectionHeaderError(fpname, lineno, line)
# an option line?
Comment thread
pslacerda marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

Expand Down Expand Up @@ -1088,6 +1114,7 @@ def _read(self, fp, fpname):
# raised at the end of the file and will contain a
# list of all bogus lines
e = self._handle_error(e, fpname, lineno, line)

self._join_multiline_values()
# if any parsing errors occurred, raise an exception
if e:
Expand Down
72 changes: 72 additions & 0 deletions 72 Lib/test/test_configparser.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -2119,6 +2119,78 @@ def test_instance_assignment(self):
self.assertEqual(cfg['two'].getlen('one'), 5)


class SectionlessTestCase(unittest.TestCase):

def fromstring(self, default_section, string):
cfg = configparser.ConfigParser(default_section=default_section)
cfg.read_string(string)
return cfg

def test_only_top_level(self):
cfg1 = self.fromstring(configparser.TOP_LEVEL, """
a = 1
b = 2
""")

self.assertEqual([], cfg1.sections())
self.assertEqual('1', cfg1[configparser.TOP_LEVEL]['a'])
self.assertEqual('2', cfg1[configparser.TOP_LEVEL]['b'])

output = io.StringIO()
cfg1.write(output)
cfg2 = self.fromstring(configparser.TOP_LEVEL, output.getvalue())

self.assertEqual([], cfg1.sections())
self.assertEqual('1', cfg2[configparser.TOP_LEVEL]['a'])
self.assertEqual('2', cfg2[configparser.TOP_LEVEL]['b'])

def test_only_regular(self):
cfg1 = self.fromstring(configparser.TOP_LEVEL, """
[sect1]
a = 1
b = 2
""")

self.assertEqual(['sect1'], cfg1.sections())
self.assertEqual('1', cfg1['sect1']['a'])
self.assertEqual('2', cfg1['sect1']['b'])

output = io.StringIO()
cfg1.write(output)
cfg2 = self.fromstring(configparser.TOP_LEVEL, output.getvalue())

self.assertEqual(['sect1'], cfg2.sections())
self.assertEqual('1', cfg2['sect1']['a'])
self.assertEqual('2', cfg2['sect1']['b'])

def test_top_level_and_regular(self):
cfg1 = self.fromstring(configparser.TOP_LEVEL, """
a = 1
b = 2
[sect1]
c = 3
d = %(a)s%(b)s%(c)s
""")

self.assertEqual(['sect1'], cfg1.sections())
self.assertEqual('1', cfg1[configparser.TOP_LEVEL]['a'])
self.assertEqual('2', cfg1[configparser.TOP_LEVEL]['b'])
self.assertEqual('3', cfg1['sect1']['c'])
self.assertEqual('1', cfg1['sect1']['a'])
self.assertEqual('123', cfg1['sect1']['d'])

output = io.StringIO()
cfg1.write(output)
cfg2 = self.fromstring(configparser.TOP_LEVEL, output.getvalue())

self.assertEqual(['sect1'], cfg1.sections())
self.assertEqual('1', cfg2[configparser.TOP_LEVEL]['a'])
self.assertEqual('2', cfg2[configparser.TOP_LEVEL]['b'])
self.assertEqual('3', cfg2['sect1']['c'])
self.assertEqual('1', cfg2['sect1']['a'])
self.assertEqual('123', cfg2['sect1']['d'])


Comment thread
pslacerda marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

class MiscTestCase(unittest.TestCase):
def test__all__(self):
support.check__all__(self, configparser, not_exported={"Error"})
Expand Down
4 changes: 4 additions & 0 deletions 4 Misc/NEWS.d/next/Library/2022-09-22-07-33-00.bpo-22253.jdo4573.rst
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
:class:`configparser.ConfigParser` now accepts unnamed sections before named
ones, if configured to do so.
Comment thread

@vadmium vadmium Mar 24, 2024

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

“accepts an unnamed section before named ones” might be clearer

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

Contributed by Pedro Sousa Lacerda and Christian Siefkes.
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.