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

Steven D'Aprano steve at pearwood.info
Wed May 4 10:20:41 EDT 2016


On Wed, May 04, 2016 at 02:03:59PM +1000, Nick Coghlan wrote:

> I was curious as to whether or not it was technically feasible to
> implement this "duplicate keys" check solely for dict displays in
> CPython without impacting other dict use cases, and it turns out it
> should be.
[...]
> All-in-all, the concept gets a +0 from me, although to allow for
> implementations that don't share CPython's distinction between dict
> displays and the normal dict constructor, any such behaviour (if
> introduced) should likely be flagged as an implementation detail that
> may vary across interpreters (as I would have been -1 if BUILD_MAP's
> implementation wasn't already independent of dict_common_update).

What do you think of MAL's suggestion of adding a CHECK_MAP op-code and 
raising a warning?

I'd be much more comfortable with a warning than an error, because I 
really don't think that duplicate keys is *necessarily* an error. I 
think Paul Moore is onto something with his example of BLUE/LIGHT_BLUE, 
even if he got the order the wrong way around :-)

This has been the documented behaviour of dicts since at least 1.5:

https://docs.python.org/release/1.5/ref/ref-7.html#HEADING7-35

and it matches the behaviour of both the dict constructor and dict 
comprehensions. I don't think anyone has made the case for turning it 
into an error, although I concede that it's perhaps worthy of a warning.

(At least, I won't object to it being a warning, provided we can turn 
it off :-)



-- 
Steve


More information about the Python-ideas mailing list