2

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'
Joost Döbken
  • 3,450
  • 2
  • 35
  • 79

1 Answers1

2

Ah, this is simply solved by adding another @dataclass(frozen=True) decorator to the child class

Joost Döbken
  • 3,450
  • 2
  • 35
  • 79