←back to thread

191 points jwilk | 3 comments | | HN request time: 0s | source
Show context
pansa2 ◴[] No.46230704[source]
I wonder whether Raymond Hettinger has an opinion on this PEP. A long time ago, he wrote: "freezing dicts is a can of worms and not especially useful".

https://mail.python.org/pipermail/python-dev/2006-February/0...

replies(8): >>46230899 #>>46230957 #>>46231064 #>>46231597 #>>46232170 #>>46234698 #>>46235104 #>>46271495 #
zahlman ◴[] No.46231064[source]
> Another PEP 351 world view is that tuples can serve as frozenlists; however, that view represents a Liskov violation (tuples don't support the same methods). This idea resurfaces and has be shot down again every few months.

... Well, yes; it doesn't support the methods for mutation. Thinking of ImmutableFoo as a subclass of Foo is never going to work. And, indeed, `set` and `frozenset` don't have an inheritance relationship.

I normally find Hettinger very insightful so this one is disappointing. But nobody's perfect, and we change over time (and so do the underlying conditions). I've felt like frozendict was missing for a long time, though. And really I think the language would have been better with a more formal concept of immutability (e.g. linking it more explicitly to hashability; having explicit recognition of "cache" attributes, ...), even if it didn't go the immutable-by-default route.

replies(5): >>46231200 #>>46231991 #>>46235637 #>>46236476 #>>46241200 #
1. FreakLegion ◴[] No.46241200[source]
> 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(1): >>46243713 #
2. zahlman ◴[] No.46243713[source]
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.
replies(1): >>46249522 #
3. FreakLegion ◴[] No.46249522[source]
It really doesn't make sense for there to be an inheritance relationship between Mapping and MutableMapping if Mapping is immutable (it isn't, of course), but the weirder part is still just that the typing machinery is cool with unhashable key types like:

  x: dict[list, int] = {}

  x[[1, 2, 3]] = 0