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

Steven D'Aprano steve at pearwood.info
Wed May 4 08:22:52 EDT 2016


On Wed, May 04, 2016 at 12:18:59AM -0400, Random832 wrote:
> On Tue, May 3, 2016, at 23:31, Chris Angelico wrote:
> > Duplicate keys in dict display
> > is more similar to duplicate keyword arguments in a function call than
> > to reassignment.
> 
> To play devil's advocate for a minute here...
> 
> Why *don't* we allow duplicate keyword arguments in a function call,
> anyway? CALL_FUNCTION doesn't seem to actually care, if I create this
> situation by monkey-patching the calling function's consts to get
> duplicate keywords. All the arguments that have been raised here for
> *allowing* duplicate keyword arguments seem to apply just as well to
> f(**{'a': 1}, **{'a': 2}) [where 'a' may not be the only key present and
> they may not be literal^Wdisplays], yet that is prohibited. Why not
> remove that check, too?

(1) Because status quo wins. In the absence of a really compelling 
reason to remove that check, we don't have to justify prohibing 
duplicate keyword args, we just have to note that it is already in place 
and so we shouldn't change it.

(2) Duplicate keys in a dict may have side-effects, which mean they do 
something. Duplicate keyword arguments don't have side-effects (not in 
the keys at least). So that's a difference.

(3) The analogy between function calls and dicts is not really that 
strong. The dict constuctor intentionally allows certain duplicates:

py> dict({'a': None}, a=2)
{'a': 2}

for good reason (think of over-riding the values provided in the input 
dict with keyword arguments), but it's not clear that there is an 
analogy for function calls. Perhaps there is, and if it is a good enough 
analogy, we might have to re-think the duplicate kwargs situation.


-- 
Steve


More information about the Python-ideas mailing list