logoalt Hacker News

FreakLegionlast Friday at 5:38 AM1 replyview on HN

> I've felt like frozendict was missing for a long time, though.

Type the dict as a mapping when you want immutability:

  x: Mapping[int, int] = {1: 1}

  x[1] = 2  # Unsupported target for indexed assignment ("Mapping[int, int]").
The only problem I've seen with this is:

  y = {}
  y[x] = 0  # Mypy thinks this is fine. Mapping is hashable, after all!
The issue here is less that dict isn't hashable than that Mapping is, though.

Replies

zahlmanlast Friday at 1:00 PM

This is because the ABC system is defined such that MutableMapping is a subtype of Mapping. Which mostly makes sense, except that if we suppose there exist Mappings that aren't MutableMappings (such that it makes sense to recognize two separate concepts in the first place), then Mapping should be hashable, because immutable things generally should be hashable. Conceptually, making something mutable adds a bunch of mutation methods, but it also ought to take away hashing. So Liskov frowns regardless.

show 1 reply