Reputation: 4035
I found the use of a frozen dataclass the most clean solution to make Python objects immutable. The implementation is really simple adding a single class decorator:
from dataclasses import dataclass
@dataclass(frozen=True)
class Immutable:
attr1: int
attr2: int
Now I want to extend the Immutable
class by introducing a new attribute attr3
:
class MyImmutableChild(Immutable):
attr3: int
But, the behavior is not as expected:
>>> immutable_obj = MyImmutableChild(attr1=1, attr2=3, attr3=5)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-2b6c18366721> in <module>
----> 1 immutable_obj = MyImmutableChild(attr1=1, attr2=3, attr3=5)
TypeError: __init__() got an unexpected keyword argument 'attr3'
Upvotes: 2
Views: 367
Reputation: 4035
Ah, this is simply solved by adding another @dataclass(frozen=True)
decorator to the child class
Upvotes: 2