Lesson 29 / 49

Dataclasses & Enums

Cut boilerplate with @dataclass for data-holding classes and use Enum for fixed sets of named constants.

@dataclass

@dataclass generates __init__, __repr__ and __eq__ from type-annotated fields, so data classes need no boilerplate.

from dataclasses import dataclass, field

@dataclass
class User:
    name: str
    age: int = 0
    tags: list[str] = field(default_factory=list)

u = User("Ada", 36)
print(u)            # User(name='Ada', age=36, tags=[])
print(u == User("Ada", 36))  # True

Enum

Enum names a fixed set of values, so code reads Status.ACTIVE instead of a magic string.

from enum import Enum

class Status(Enum):
    PENDING = "pending"
    ACTIVE = "active"

s = Status("active")
print(s, s.name, s.value)   # Status.ACTIVE ACTIVE active

Use field(default_factory=list) for mutable defaults. Add frozen=True to make a dataclass immutable and hashable.

Quick check

Quick check: Which methods does @dataclass generate automatically?

  • __init__, __repr__ and __eq__
  • Only __del__
  • __enter__ and __exit__
  • None of them
Answer

__init__, __repr__ and __eq__ — Dataclasses generate these from the annotated fields.