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

Rob Cliffe rob.cliffe at btinternet.com
Tue May 3 22:00:22 EDT 2016

On 04/05/2016 02:40, Ethan Furman wrote:
> On 05/03/2016 05:23 PM, Steven D'Aprano wrote:
>> On Tue, May 03, 2016 at 02:27:16PM -0700, Ethan Furman wrote:
>>> On 05/03/2016 01:43 PM, Michael Selik wrote:
>>>> On Tue, May 3, 2016 at 4:00 PM Ethan Furman wrote:
>>>>> Which seems irrelevant to your argument: a duplicate key is a 
>>>>> duplicate
>>>>> key whether it's 123 or 'xyz'.
>>>> If an expression includes an impure function, then the duplication of
>>>> assignment to that key may have a desirable side-effect.
>>> I'm willing to say that should be done with an existing dict, not in a
>>> literal.
>> But are you willing to say that the compiler should enforce that
>> stylistic judgement?
>>>> How would you handle an expression that evaluates differently for each
>>>> call? For example:
>>>>      {random(): 0, random(): 1}
>>> Easy:  Don't Do That.  ;)
>> I see your wink, so I presume you're not actually suggesting that the
>> compiler (1) prohibit all function calls in dict displays, or (2)
>> hard-code the function name "random" in a black list.
> Indeed.
>> So what are you actually suggesting? Michael is raising a good point
>> here. If you don't like random as an example, how about:
>> d = {spam(a): 'a', spam(b): 'BB', spam(c): 'Ccc'}
> >
> > I'm intentionally not giving you the values of a, b or c, or telling
> > you what spam() returns. Now you have the same information available
> > to you as the compiler has at compile time. What do you intend to do?
> Since the dict created by that dict display happens at run time, I am 
> suggesting that during the process of creating that dict that any 
> keys, however generated or retrieved, that are duplicates of keys 
> already in the dict, cause an appropriate error (to be determined).
Sorry, I favour raising an error for duplicate *literal constant* keys 
(presumably at compile time).  But I think making the above example 
cause a runtime error if two keys happened to be equal would break too 
much existing code.

More information about the Python-ideas mailing list