News for hackers. Stuff that matters.
Re:Python Design Patterns (2018) by rmbyrro on Sunday March 13, 2022 @08:33PM (#30667249)
> Don't use classes for information. Use regular data structures (dict, list, tuple, set) and use functions to manipulate them.

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...

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.
Re:Python Design Patterns (2018) by rmbyrro on Monday March 14, 2022 @04:13AM (#30669683)
Wasn't aware of this feature in dataclasses, that can be helpful in a few cases, thanks for pointing out
Re:Python Design Patterns (2018) by ciupicri on Sunday March 13, 2022 @09:37PM (#30667606)
> 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...

Re:Python Design Patterns (2018) by rmbyrro on Monday March 14, 2022 @03:55AM (#30669579)
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.

Re:Python Design Patterns (2018) by ciupicri on Monday March 14, 2022 @03:11PM (#30676818)
It sounds like what you really want is an efficient way of copying dictionaries, perhaps copy on write, something like the cowdict [1] project.

[1]: https://pypi.org/project/cowdict/