4 ms·
It's easy to do immutability in python, just use NamedTuple for classes and tuple instead of list
by wlpu 5y ago
It's easy to do immutability in python, just use NamedTuple for classes and tuple instead of list
- macintux 5y agoI’ll research those, thanks. Any suggestions for OSS projects that do so today?
- gravypod 5y agoThis is a good talk that demos NamedTuple: https://www.youtube.com/watch?v=wf-BqAjZb8M https://www.youtube.com/watch?v=wf-BqAjZb8M
- japanuspus 5y ago...or `dataclass(frozen=True)` if you need the ergonomics. For non-primitive members, `frozenset` is in the standard library, but frozen dictionaries are unfortunately lacking.
- joshuamorton 5y agoPlease don't do this, there are far better approaches. Use dataclasses/attrs that are frozen for immutable record types. (Specifically avoid namedtuples unless you're hoisting a tuple to a real record. Record types also being a weird union with a tuple is...oft confusing) For immutable basic data types, adopt type annotations and prefer to use sequence/iterable and mapping to direct didn't/list types. These provide statically verifiable immutability and also allow begin to encourage useful async-friendly patterns.
- rurp 5y agoI second this. My current job is the first place I've worked where the convention is to use NamedTuples for most things I've seen dicts used for on past projects and I quite like the pattern. It both makes the code more readable and avoids a number of subtle bugs that can crop up.
- shabbyrobe 5y agoSince PEP 591 [1], if using mypy with Python 3.8+ or the typing_extensions module, you can also take advantage of typing.Final, which lets you statically verify something isn't changed. The catch is that it isn't enforced at runtime. [1]: https://www.python.org/dev/peps/pep-0591/
- dexterous 5y agoSure, we'll do all that. In the mean time, could you please get started on getting the _rest_ of the community to adopt that as a well established idiom and then also have them initiate efforts to adapt popular libraries/frameworks so that they implement the adopted idioms? Would Thursday be a good time to checkpoint on this? Thank you so much.