Using mutable dataclass

Use frozen=True to make the dataclasses immutable and hashable.

With @dataclass(frozen=True) then assigning to fields after the object has been instantiated will raise a FrozenInstanceError. This emulates read-only frozen instances, and gives the advantages of immutability.

Frozen dataclass will also generate a __hash__() method on the class. This allows the instance to be used in set and dict objects. Attempting to add a non-hashable object to a dict will result in TypeError: unhashable type

An immutable object is an object that cannot be modified. Strings are an example of an immutable object. There are some advantages to immutability:

  • Thread safety: Threads can safely share immutable objects because none of the threads can mutate the object.
  • Less moving parts: A developer can see the object is immutable so they can remove "what if this gets changed" from their mental model of how the code works.
  • Less side effects: Mutable objects may be inadvertently updated by buggy code, resulting in hard-to-debug bugs. This is not possible with immutable objects.

If our GitHub code review bot spots this issue in your pull request it gives this advice:

code-review-doctorbotsuggested changes just now
from dataclasses import dataclass
Suggested changes
Expand 2 lines ...
Commit suggestion

Use frozen=True to make the dataclasses immutable and hashable.

Read more
class FooBarClass:
We're your Python code review copilot. Get code improvements right in your pull request with our GitHub code review bot.

Configuring this check

Code Review Doctor will run this check by default. No configuration is needed but the check can be turned on/off using check code freeze-dataclasses in your pyproject.toml file.

Read more about configuring Code Review Doctor.