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

Franklin? Lee leewangzhong+python at gmail.com
Fri May 6 08:56:36 EDT 2016


Late, but here are a few more notes:

1. The gnumpy package (for Py2) used expressions in a `set`
constructor which could evaluate to duplicates. It isn't hard to
imagine a similar trick with `dict`, though I don't know if it'd be as
useful.
    From gnumpy.py:
    ```
    _floatTypes = set((types.FloatType, numpy.float64, numpy.float32,
getattr(numpy, 'float128', numpy.float64), getattr(numpy, 'float96',
numpy.float64)))
    ```

    Refactored a bit:
    ```
    _floatTypes = {float, numpy.float64, numpy.float32, getattr(numpy,
'float128', float), getattr(numpy, 'float96', float)}
    ```


2. Even if the warning/error is compiler-only, `eval` and `exec` would
have the same warning/error, and they are NOT always evaluating
dev-written source code. (Though you can argue that `exec` and `eval`
on strings are where you should be on high alert with regard to data
validation.) On the other hand, a linter is only run on
manually-written code.


3. A compile-time check doesn't necessarily give a false sense of
security. It just needs the proper wording to indicate that it's a
compile-time check. "Warning: Duplicate (constant|literal|string
literal) keys detected."


More information about the Python-ideas mailing list