the full guide

dataclasses and enum

A dataclass is a class that mainly holds data, and Python writes __init__, __repr__ and __eq__ for it automatically. An Enum defines a fixed set of named values, so you can't accidentally use an invalid one.

8 min Intermediate

What you need: The earlier topics of this module.

Definition

A dataclass is a class that mainly holds data, and Python writes __init__, __repr__ and __eq__ for it automatically. An Enum defines a fixed set of named values, so you can't accidentally use an invalid one.

In simple words

A dataclass saves you typing the same boring setup in every class. An Enum is a dropdown list in code: the status can be PAID or PENDING, and never the typo "PAYED".

Why it matters

They remove lots of repeated code and many bugs, and modern Python projects use them widely, including for configs in ML training.

How it works

In code

dataclass_demo.py
from dataclasses import dataclass, field
from enum import Enum

class Status(Enum):
    PAID = "paid"
    PENDING = "pending"

@dataclass
class Order:
    customer: str
    amount: float
    status: Status = Status.PENDING
    items: list[str] = field(default_factory=list)

a = Order("Riya", 500.0)
print(a)
print(a == Order("Riya", 500.0))

a.status = Status.PAID
print(a.status.name, a.status.value)

try:
    Status("payed")
except ValueError as error:
    print("Refused:", error)

Output

Order(customer='Riya', amount=500.0, status=<Status.PENDING: 'pending'>, items=[])
True
PAID paid
Refused: 'payed' is not a valid Status

Common mistakes

  • Using raw strings for status values, so typos go unnoticed.
  • Writing a mutable default directly in a dataclass.

Check yourself

Question 1

1. What does @dataclass generate?

Question 2

2. Why use an Enum for status?

Summary

  • Dataclasses write the setup code for you.
  • Enums make a fixed set of valid values.

Finished reading?

Sources: Python docs: dataclasses