by notpushkin · 2y ago · 0 comments
This fits pretty well with a lot of other stuff in Python (e.g. there’s no real private members in classes). There’s a bunch of escape hatches that you should avoid (but that can still be useful sometimes), and those usually are pretty obvious (e.g. if you see code using object.__setattr__, something is definitely not right).
Can’t tell whether this is good design or not, but personally I like it.
In [1]: from dataclasses import dataclass
In [2]: @dataclass(frozen=True)
...: class Foo:
...: a: int
...:
In [3]: foo = Foo(5)
In [4]: foo.a = 10
FrozenInstanceError: cannot assign to field 'a'
In [5]: setattr(foo, "a", 10)
FrozenInstanceError: cannot assign to field 'a'
In [6]: object.__setattr__(foo, "a", 10)
In [7]: foo.a
Out[7]: 10