[Python-Dev] ConfigParser mangles keys with special chars
Steven D'Aprano
steve at pearwood.info
Sat Apr 26 13:23:11 CEST 2014
On Sat, Apr 26, 2014 at 01:59:27AM -0400, Fred Drake wrote:
> On Sat, Apr 26, 2014 at 1:34 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> > I think that a line beginning with "#spam" is ambiguous, it isn't clear
> > if it is intended as a comment "spam" or a key starting with #, so by
> > the Zen, configparser should refuse to guess.
>
> Seriously?
Perhaps I could have worded my post more clearly, but yes.
In context, we were talking about a situation where the user creates a
key value pair. Copying from the OP's initial post:
>>> cp = configparser.ConfigParser()
>>> cp.read_dict({'DEFAULT': {';foo': 'bar'}})
>>> cp.write(sys.stdout)
[DEFAULT]
;foo = bar
The intent of the creator of the ConfigParser was for a key ";foo" with
value "bar", and that is the way it is treated while still in memory.
It's only when reading it back from a file does it become treated as a
comment. There's no way to tell whether the line ";foo = bar" *in a
file* came from a key ";foo" with value "bar", or from a genuine comment
that merely happens to look like key=value.
The obvious way to avoid the ambiguity is to disallow keys beginning
with a comment prefix. Then ";foo = bar" cannot represent the key
";foo", because such a key is illegal.
> Perhaps the second paragraph here could be strengthened a little:
> https://docs.python.org/3/library/configparser.html#supported-ini-file-structure
>
> But that seems clear to me. Lines starting with the comment prefix
> are comments.
But the entry in question wasn't a line, it was a key=value pair in a
dict. Here's that line again:
cp.read_dict({'DEFAULT': {';foo': 'bar'}})
or it could have been:
cp['DEFAULT'][';foo'] = 'bar'
Either way, if there's no way to escape comment characters, I think it
is a bug that you can insert illegal keys into the cp object in the
first place.
--
Steven
More information about the Python-Dev
mailing list