[Python-Dev] Immutability vs. hashability

Guido van Rossum guido at python.org
Mon Feb 5 00:18:25 EST 2018


That's a lot to read between the lines. I was unhappy that Chris took the
statement that immutability and hashability are equivalent, claimed that
most people think of it that way, and did not point out that it was false,
thereby making the impression that he wasn't aware of the difference.

The way I think of it generally is that immutability is a property of
types, while hashability is a property of values.

I don't want the original debate (about what to do with hash=True for
dataclasses) to be spread across multiple threads so I'll reply separately
there.

On Sun, Feb 4, 2018 at 5:54 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:

> On 5 February 2018 at 08:31, Guido van Rossum <guido at python.org> wrote:
> > On Sun, Feb 4, 2018 at 11:59 AM, Chris Barker - NOAA Federal
> > <chris.barker at noaa.gov> wrote:
> >>
> >> I think the folks that are concerned about this issue are quite right
> >> — most Python users equate immutable and hashable—so the dataclass API
> >> should reflect that.
> >
> > Since they are *not* equivalent (consider a tuple containing a list) I'm
> not
> > at all convinced that any API in the core language should "reflect" this
> > misconception, depending on how you meant that.
>
> Lists are themselves mutable, and hence inherently unhashable.
>
> Tuples are themselves immutable, and hence hashable if their contents are.
>
> I interpret Chris's comment as saying that data classes should behave
> the same way that the builtin container types do:
>
> * if the data class itself is mutable (frozen=False, comparable to
> list, dict, set), then it is *not* hashable (unless you explicitly
> implement __hash__)
>
> * if the data class itself is immutable (frozen=True, comparable to
> tuple or frozenset), then whether or not it is hashable depends on
> whether or not the field values are hashable.
>
> It's the ability to ask the interpreter to guess what you mean
> "frozen=False, hash=True" that creates the likelihood of confusion.
>
> Whereas if we leave out the "hash=True" option entirely, then the most
> natural way to obtain a partially-mutable record, which has a fixed
> comparison key and selectively mutable state, then the recommended way
> of handling that would be through containment, where the mutable state
> is moved out to a subrecord that gets excluded from hashes and
> comparisons.
>
> Cheers,
> Nick.
>
> --
> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
>



-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20180204/6c41e98f/attachment.html>


More information about the Python-Dev mailing list