What does @dataclass(frozen=True) give you (with default eq=True)?
Options
- Mutable instances with a generated
__hash__ - Immutable instances that are also hashable (Correct option)
- Instances that cannot be compared
- Automatic validation of field types
Answer
Immutable instances that are also hashable
Why
@dataclass writes __init__, __repr__ and __eq__ for you from the list of fields.
frozen=True makes objects read-only: changing a field raises an error.
Because a frozen object never changes, its hash stays valid, so Python also creates __hash__ and you can use the object in sets or as a dict key. Note: dataclasses do not validate types (Pydantic does).
Remember
frozen dataclass = immutable + hashable.