[Python-Dev] Dataclasses and correct hashability

Elvis Pranskevichus elprans at gmail.com
Thu Feb 1 19:34:19 EST 2018

There appears to be a critical omission from the current dataclass 
implementation: it does not make hash=True fields immutable.  

Per Python spec: 

"the implementation of hashable collections requires that a key’s hash 
value is immutable (if the object’s hash value changes, it will be in 
the wrong hash bucket)"


    import dataclasses

    class A:
        foo: int = dataclasses.field(hash=True, compare=True)

    a = A(foo=1)

    s = set()
    s.add(a)   # s == {a}
    a.foo = 2

    print(a in s)
    print({a} == s}
    print(s == s)

    # prints False False True

This looks to me like a clearly wrong behavior.


More information about the Python-Dev mailing list