Closed
Description
Bug report
Checklist
- I am confident this is a bug in CPython, not a bug in a third-party project
- I have searched the CPython issue tracker, and am confident this bug has not been reported before
A clear and concise description of the bug
When trying to parse an INI with an indented key that follows a no-value key, an AttributeError is raised
import configparser
lines = [
'[SECT]\n',
'KEY1\n',
' KEY2 = VAL2\n', # note the Space before the key!
]
conf = configparser.ConfigParser(
comment_prefixes ="",
allow_no_value =True,
strict =False,
delimiters =( '=', ),
interpolation =None,
)
conf.read_file( lines, "test" )
print( conf.__dict__[ '_sections' ] )
File "C:\Python311\Lib\configparser.py", line 1076, in _read
cursect[optname].append(value)
^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'append'
The reason is that ConfigParser assumes the second key is a continuation line and therefore further assumes that cursect[optname]
is initialized in the following check:
if (cursect is not None and optname and
cur_indent_level > indent_level):
cursect[optname].append(value)
Suggested fix: add a check for cursect[optname] is not None
:
if (cursect is not None and optname and
cursect[optname] is not None and
cur_indent_level > indent_level):
cursect[optname].append(value)
With this check added, the print will output:
{'SECT': {'key1': None, 'key2': 'VAL2'}}
If the suggested fix is not acceptable, please consider to add a check and maybe raise a ParsingError
, but making an assumption about cursect[optname]
and let it raise an AttributeError is just not a good thing, IMHO.
Your environment
- CPython versions tested on: 3.7, 3.9, 3.11.2 (Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] on win32)
- Operating system and architecture: Windows 10 Pro, 64 bit