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

Franklin? Lee leewangzhong+python at gmail.com
Wed May 4 02:04:03 EDT 2016


On Wed, May 4, 2016 at 12:40 AM, Michael Selik <michael.selik at gmail.com> wrote:
>
> On Wed, May 4, 2016 at 12:19 AM Random832 <random832 at fastmail.com> 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.
>>
>> If we can blithely pass the same constant key twice to BUILD_MAP, why
>> *shouldn't* we be able to do the same to CALL_FUNCTION?
>
> Because keyword arguments can only be valid identifiers, rather than
> expressions. There's absolutely no reason to use the same identifier as
> keyword twice, but there could be some oddball reasons to use the same
> expression as dict key twice.

The uniqueness rule applies to splatted args, too.

    def printn(*args, **kwargs):
        print(*args, **kwargs, sep='\n')

    printn('hello', 'world', sep='\n')
    # => TypeError: print() got multiple values for keyword argument 'sep'

Not a very useful example, but if you want to override or ignore
incoming kwargs...

......

For semantics, I see a few possibilities (either error or warning):

    0. Detect duplicate literal keys at compile-time.

    1. Detect duplicate literals and hereditarily-literal displays and
expressions at compile-time. (This includes keys which are tuple
displays containing only hereditarily-literal elements, expressions of
literals, and, er, implicit string concatenation like `'hello' " "
'world'`. As keys, these things are guaranteed to be immutable.)

    2. Also statically analyze for duplicate variables as keys. (I
think if it's a local variable that isn't captured by a closure using
`nonlocal`, it is safe to assume that it's constant for that dict
display.)

    3. Constant-folding. (This leads to the dark path of static
analysis shipping with the language.)

    float('inf'). Analyze at runtime.

    1j. Declare that duplicate keys in a dict display causes
underdefined behavior, and let interpreters decide how to handle it.

    -1. Identical expressions are warned against as duplicate keys.

(By the way, anything that happens for dicts should also happen for sets.)


More information about the Python-ideas mailing list