Repaso
EspaƱol
PythonIntermediatePY-23

What does @dataclass(frozen=True) give you (with default eq=True)?

Options

  1. Mutable instances with a generated __hash__
  2. Immutable instances that are also hashable (Correct option)
  3. Instances that cannot be compared
  4. 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.

Key terms

Practice this question in Repaso