Re:Python Design Patterns (2018)
by galoisscobi on Sunday March 13, 2022 @09:19PM
(#30667506)
Frozen dataclass instances (https://docs.python.org/3/library/dataclasses.html#frozen-in...) might be of help.
Wasn't aware of this feature in dataclasses, that can be helpful in a few cases, thanks for pointing out
> class types.MappingProxyType(mapping)
> Read-only proxy of a mapping. It provides a dynamic view on the mapping’s entries, which means that when the mapping changes, the view reflects these changes.
https://docs.python.org/3/library/types.html#types.MappingPr...
This can be helpful in some cases, but it's precisely what I sometimes need to avoid, which is protecting a dictionary and having changes affecting only its own scope.
If function A passes a dict to function B, I would like:
1) Function A to keep the dict intact while function B can manipulate its content;
2) Function A can change the dict after passing to B, and B still keep the original copy, unaware of A's later changes.
One way of doing this is by deep copying dictionaries around, but it can easily become a big performance issue.
It sounds like what you really want is an efficient way of copying dictionaries, perhaps copy on write, something like the cowdict [1] project.
One problem is many of these datastructures are easy to mutate. When I need to ensure immutability to a dictionary, for instance - quite often - I can't avoid wrapping it in a class and setting up an interface to lock down mutation.
If Python had a way to declare immutable datastructure, similarly to Clojure, it would make life a lot easier...