[Python-ideas] dictionary constructor should not allow duplicate keys

Chris Angelico rosuav at gmail.com
Tue May 3 23:31:33 EDT 2016


On Wed, May 4, 2016 at 1:23 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> Why single out just one to raise an exception?  My guess is that it is
> partly from mistakenly thinking of the one as a like a lexer literal rather
> than as runtime code.

But the lexer's definition of "literal" is extremely narrow, and
doesn't reflect the way people think about them. Most people's idea of
a literal is closer to what ast.literal_eval can accept:

Help on function literal_eval in module ast:

literal_eval(node_or_string)
    Safely evaluate an expression node or a string containing a Python
    expression.  The string or node provided may only consist of the following
    Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
    sets, booleans, and None.

>>> ast.literal_eval("[1,-2,(3+4j)]")
[1, -2, (3+4j)]

Neither -2 nor (3+4j) is technically a literal, and certainly list
display isn't a literal, but "literal_eval" is happy to parse them.
And that's how people think about them. Duplicate keys in dict display
is more similar to duplicate keyword arguments in a function call than
to reassignment. Can you show any good code that reuses a key in a
single dict display? Wouldn't it at best be code smell?

That doesn't necessarily mean that the compiler should stop you from
doing it; but I do think that there's a fundamental difference in
expectation here. And if the check happens, it wants to be a
compile-time check, not a run-time one.

ChrisA


More information about the Python-ideas mailing list