frozen=True to make the
dataclasses immutable and hashable.
@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.
dataclass will also generate a
__hash__() method on the class. This allows the instance to be used in
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:
If our GitHub code review bot spots this issue in your pull request it gives this advice:
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.