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

Chris Angelico rosuav at gmail.com
Tue May 3 22:22:58 EDT 2016


On Wed, May 4, 2016 at 11:54 AM, Rob Cliffe <rob.cliffe at btinternet.com> wrote:
> In a dictionary literal, it should be a syntax error to have two keys which
> are literal int or literal basestring values and which are equal.
>
> (I say basestring, meaning that    { 'lion' : 'x', u'lion' : 'y' }    would
> be an error.  So of course would    { 18L : 'x', 0x12 : 'y' }    etc.)
>
>     (7) If the proposal is accepted, should it appear complete in the next
> Python release, or should there be a more gradual adoption process?

This is the very soonest it can possibly appear, which means that
notions of "long integer" and "basestring" aren't really applicable -
they're Python 2 concepts. Text strings and byte strings in Python 3
are completely different:

>>> {'lion': 'x', b'lion': 'y'}
{'lion': 'x', b'lion': 'y'}

and there aren't any short/long integers. So here's my rewording of
your proposal:

***
Identical string or numeric literals used as keys in the same
dictionary display MAY cause a SyntaxError.
***

Whether constants get folded before this check, and whether {1:'x',
1.0:'y'} causes an error, can be implementation-defined.
Implementations are welcome to not check for this at all if they wish.

Valid types for this check would be str, bytes, int, float, and
complex - there's no way that the same literal could result in unequal
values, so these are all safe.

I'm still not sure whether I'm in favour of the proposal or not, but
that's how I'd word it.

ChrisA


More information about the Python-ideas mailing list