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

Chris Angelico rosuav at gmail.com
Wed May 4 08:24:06 EDT 2016


On Wed, May 4, 2016 at 10:08 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> Let's say I write something like this:
>
> with open(path) as f:
>     d = {
>          f.write(a): 'alpha',
>          f.write(b): 'beta',
>          f.write(c): 'gamma',
>          f.write(d): 'delta',
>          }
>
> and purely by my bad luck, it turns out that len(b) and len(c) are
> equal, so that there are two duplicate keys. Personally, I think this is
> silly code, but there's no rule against silly code in Python, and maybe
> I have a (good/bad/stupid) reason for writing this. Maybe I don't care
> that duplicate keys are over-written.
>
> If we introduce your rule, that's the same as saying "this code is
> so awful, that we have to ban it... but only *sometimes*, when the
> lengths happen to be equal, the rest of the time it's fine".
>
> Are you okay with saying that? (Not a rhetorical question, and you are
> allowed to say "Yes".)
>

My response: Yes. I am okay with saying that. Because the question
really is: What is this dictionary being used for? Why are you using
keys that might, under some circumstances, overwrite each other? The
point of a dict is to retrieve values when given keys. How can you do
this, if those keys might collide? I've yet to see any real-world code
that does this usefully, in a dict display. And the best "well, maybe
if" examples have all involved generated code, so it wouldn't be hard
to change your codegen to use this instead:

d = dict((
    (f.write(a), 'alpha'),
    (f.write(b), 'beta'),
    (f.write(c), 'gamma'),
    (f.write(d), 'delta'),
))

which, of course, will continue to function as expected.

ChrisA


More information about the Python-ideas mailing list