4 ms·
You can use: > @dataclass(frozen=True) to create an immutable data class.
by throwaway2037 2y ago
You can use:
> @dataclass(frozen=True)
to create an immutable data class.
- maleldil 2y agoWhile that works (and I use it extensively), it's a bit hacky. You have to use `object.__setattr__` to set attributes in `__init__` or `__post_init__`, which looks so wrong.
- maxbond 2y agoI think the cleaner alternative would be to use a static or class method as an alternative constructor and use the init the dataclass decorator provides for you. Eg something like: @dataclass(frozen=True) class Foo: bar: int baz: str @classmethod def new(cls, bar: int) -> "Foo": baz = calculate_baz(bar) return cls(bar, baz) foo = Foo.new(10)
- throwaway2037 2y agoWhat is wrong with a static factory method?