What's the difference between @dataclass(frozen=True)
and @dataclass(frozen=False)
? When should I use which?
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.
Dataclasses resemble a lot with NamedTuples however namedtuples are immutable whereas dataclasses aren't (unless the frozen parameter is set to True.)
Modifying fields after initialization with __post_init__ The __post_init__ method is called just after initialization. In other words, it is called after the object receives values for its fields, such as name , continent , population , and official_lang .
A data class is a class typically containing mainly data, although there aren't really any restrictions. It is created using the new @dataclass decorator, as follows: from dataclasses import dataclass @dataclass class DataClassCard: rank: str suit: str.
In Python, "frozen" means an object cannot be modified. For example, consider set
and frozenset
:
>>> s = set((1, 2, 3))
>>> s
{1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> fs = frozenset((1, 2, 3))
>>> fs
frozenset({1, 2, 3})
>>> fs.add(4)
...
AttributeError: 'frozenset' object has no attribute 'add'
Likewise, creating a dataclass
with frozen=True
means its instances are frozen and cannot be changed.
Be aware that frozen
only applies to the dataclass instance itself – a frozen
dataclass can contain mutable items such as lists, and a regular dataclass can contain frozen/immutable items such as tuples.
The point of frozen objects is to avoid accidental modification, and to guarantee a consistent value.
frozen
reveals accidental modification via an immediate error.dict
. A frozen
dataclass is by default hashable and suitable as a dict
key.from dataclasses import dataclass
@dataclass(frozen=True)
class Frozen:
x: int
y: int
named_points = {Frozen(0, 0): "Origin"}
Note that hashability does not just depend on the dataclass but is recursive – a frozen
dataclass containing a list
is not hashable, because the list
is not hashable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With