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
models.py
1
+
from dataclasses import dataclass
2
+
	
3
+
@dataclass

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

Read more
Suggested changes
-
@dataclass
+
@dataclass(frozen=True)
Expand 2 lines ...
Commit suggestion
4
+
class FooBarClass:
5
+
    pass
Update models.py

Instantly check if you have this issue for free

    Works with tools you use

    Read about how it works.