Semi-immutable Python objects with frozen dataclasses


Python tip:

You can freeze instances of a class decorated with dataclass by setting frozen to True.

https://docs.python.org/3/library/dataclasses.html#frozen-instances

An error will be raised if you try to assign a new value to any of attributes.

For example:

from dataclasses import dataclass


@dataclass(frozen=True)
class Post:
    title: str
    content: str


post = Post(title="Happy new year", content="2020 is finally over")

post.title = "Awesome new year"

"""
Traceback (most recent call last):
  File "example.py", line 12, in <module>
    post.title = "Awesome new year"
  File "<string>", line 4, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'title'
"""