Repository navigation
ConfigParser does not handle files without sections #66449
Description
Activity
ConfigParser does not handle files that specify options in the "global" section (first option specified before any section is). This configuration "behavior" is present in the configuration files in the wild [1, 2], and while the naive workaround is simple, ... really?!
The support for section-less configuration would also play nice with various "POSIX-compatible config files" (think /etc/default/*, /etc/os-release, ...).
Ideally, the support could be enabled by default or only when
strict=Falseconstructor argument is supplied. The options in this global section could likely be accessed in the empty ('') section, e.g.config.get('', 'option').Thus, ConfigParser could finally really replace the venerable ConfigObj 3.
- addedtype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or errorstdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directory
on Aug 22, 2014 That's an interesting feature request. Parsing it only while
strict=Falsesounds like a good plan.- addedtype-featureA feature request or enhancementA feature request or enhancementand removedtype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
on Aug 22, 2014 I, for one, would actually prefer if global options were parsed by default and MissingSectionHeaderError was deprecated instead.
From what little specification available, INI format does **not** require options be in sections [4, 5].Additionally, "Linux and Unix systems also use a similar file format for system configuration" 6 and allowing global options being a (very sane) default would nicely fill this use case as well.
In general, the format is not well defined 6, so choice of name
strictfor an argument is kind of odd too. What is it conforming to?It may be my sole opinion that parsing global options by default into a '' (or appropriate) section and deprecating MissingSectionHeaderError would benefit everyone [2, 9] and hinder few if any one at all [8, 9]. YMMV.
It looks like this feature request tries to change an existing (ancient) module into something it isn't. At the very least can you point to a spec for the syntax of "POSIX" config files? I always thought they were essentially shell scripts, which suggests that they might have a more complex (and different) quoting syntax than ConfigParser, so there might be cases where the interpretation of a line in a POSIX config file would be different than the interpretation of the same line in a .ini file.
It's not unreasonable as a new feature, but the default behaviour shouldn't change. It matches ini files (like it or not, ConfigParser parses ini-style files - the docs even say so), and sectionless values are not standard ini format.
I'd suggest a new __init__ option, allow_unnamed_section (default False) that permits variables to be placed before the first section header. I'd further suggest that the names be treated as if they were in a section with name '', for consistency of access with other sections.
It's plausible that people might want the defaults section to be the unnamed section. If so, that could be another option, default_is_unnamed (default False, if True this implies allow_unnamed_section). But I'm not sure the additional complexity is worth it.
The MS function GetPrivateProfileString appears to require sections.
http://msdn.microsoft.com/en-us/library/ms724353.aspx
On the other hand, it does not appear to do interpolation, so we have already not restricted ourselves to the MS function.In looking through the .ini files in my game directory, which includes some old games, I found a couple with no section header. So such files do exist in the wild. I am dubious that there are any with a mixture of both sections and additional option lines at the top without a section.
Anyone writing an app and planning to parse a .ini file can add [Start] or [Setup] at the top. So there is only an issue for 3rd party software parsing a file without.
I think a more useful new configparser feature would be to keep comment lines and write them back out after a configuration is changed.
I am dubious that there are any with a mixture of both sections and
additional option lines at the top without a section.rsyncd.conf [1] is one such example, and I wouldn't say there aren't
countless more in the wild.Anyone writing an app and planning to parse a .ini file can add [Start] or
[Setup] at the top.Indeed. Here lies the problem of this unfortunate issue:
MissingSectionHeaderError is only ever caught [9] to mitigate this **awful
default behavior** and attach a dummy section at the top, as you say. Or
can anyone care to propose another relevant use case for this poorly (un-)
thought through exception?I think a more useful new configparser feature would be to keep comment
lines and write them back out after a configuration is changed.While this is very much off-topic, configobj [3] does too seem to have done
so since ages.Microsoft Windows INI files, "POSIX-compatible config files", and other formats (e.g. Java properties files) use different methods for escaping, quoting, line continuing, interpolations, etc. Actually there are more differences than similarity between them.
I don't like the idea to magically introduce a '' section since this behaviour would be confusing for interpolation and not particularly discoverable by programmers. Let alone bikeshedding if this should rather be a None section.
Using DEFAULTSECT for this purpose is equally wrong since it would silently inject default values to every section, which may or may not be desirable.
All in all, it comes down to the question whether the programmer expects section-less configuration. If not, the '' section will not be helpful anyway. If yes, then it's desirable to be able to specify a section name for global options at *read time*. Symmetrically, the user could specify which section name to omit during configuration writing. I like that since it's explicit and more composable than a blanket global section. It would also be 100% backwards compatible.
I'll prepare a patch for this idea so we can see how good this API looks like in practice.
I read the rsyncd.conf doc at http://linux.die.net/man/5/rsyncd.conf (linked from the StackOverflow question). These files are not .ini files. However, I believe the parsing rules are mostly compatible with RawConfigParser, or could be made so by using existing customization options, including subclassing.
The sectionless options are called 'global options' for one of two different reasons. Some, selected from a predefined list of startup options, act as if they were in a [STARTUP] section. Others, selected from a predefined list of module options, act as if they were in a [DEFAULT] section. The latter provide alternate default value for options in the various [<module>] sections.
We clearly should not directly support the specialized rules of rsyncd.conf. But if, as kernc requests, RawConfigParser gathered sectionless options into a '' section, users could probably work with these files. The details would be up to them, or a config_unix module writer. The same comment applies to other files, including .ini files with sectionless options.
Łukasz, the only one bikeshedding '' is you. I do not see any need for a new API and I think it just confuses this issue. Reading and writing sectionless options via a '' section should be sufficient to work with .ini files.
To me, the remaining question is whether to retain configparser.MissingSectionHeaderError. The problem with piggy-backing its optional use on the 'strict' parameter is that someone might want to reject duplicates while reading sectionless options. But it ia a plausible idea.
As an aside, the documentation for MissingSectionHeaderError is currently a bit confused. The docstring correctly says "Raised when a key-value pair is found before any section header." The doc incorrectly says "Exception raised when attempting to parse a file which has no section headers." I tested and it is indeed raised even when there is a section header after an initial option line. The exception message is also wrong: "File contains no section headers." The latter two should really say that the files does not *start* with a section header (ignoring comment lines), or use the wording of the docstring.
8 remaining items
There are cases of INI-like files but with other extensions (eg. mdp file https://manual.gromacs.org/current/reference-manual/file-formats.html#mdp)
- added 2 commits that reference this issue
on Apr 2, 2024 This functionality is now available in the backport (version 7, available for Python 3.8+). Feel free to give it a test drive in your environment so we can work out any bugs.
Hi, just chiming in because I really love this new feature - however, I haven't managed to create a new INI file from scratch with an unnamed section yet. Is this possible? Here are my futile attempts with configparser 7.0.0 from backports:
Python 3.12.4 (tags/v3.12.4:8e8a4ba, Jun 6 2024, 19:30:16) [MSC v.1940 64 bit (AMD64)] on win32 >>> from backports.configparser import UNNAMED_SECTION, ConfigParser >>> cp = ConfigParser(allow_unnamed_section=True) >>> cp.set(UNNAMED_SECTION, "option1", "hello world") Traceback (most recent call last): super().set(section, option, value) raise NoSectionError(section) from None backports.configparser.NoSectionError: No section: <UNNAMED_SECTION> >>> cp.add_section(UNNAMED_SECTION) File "C:\Users\kerling\AppData\Local\pypoetry\Cache\virtualenvs\non-package-mode-l42eA81v-py3.12\Lib\site-packages\backports\configparser\__init__.py", line 1294, in _validate_value_types raise TypeError("section names must be strings") TypeError: section names must be strings >>> cp[UNNAMED_SECTION]["option1"] = "hello world" Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\kerling\AppData\Local\pypoetry\Cache\virtualenvs\non-package-mode-l42eA81v-py3.12\Lib\site-packages\backports\configparser\__init__.py", line 1070, in __getitem__ raise KeyError(key) KeyError: <UNNAMED_SECTION> >>> cp[UNNAMED_SECTION] = { "option1": "hello world" } >>> cp.sections() ['<UNNAMED_SECTION>'] >>> import io >>> fp = io.StringIO() >>> cp.write(fp) >>> fp.getvalue() '[<UNNAMED_SECTION>]\noption1 = hello world\n\n'@mtnpke I opened a new issue to track your missed expectation. As far as I understand, the support was for reading unnamed sections and not authoring them. That's not to say it can't be added, but I think we should track it as a separate issue (on the near 10 year anniversary of this one).
- added a commit that references this issue
on Sep 9, 2024 - added a commit that references this issue
on Sep 24, 2024 Python 3.13 came with this feature, so I think this issue can be closed. Or is there some pendency?
Reacted by David Liu
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
Linked PRs