C
Python/OOP/Lesson 19

@dataclass — Boilerplate Automation (PEP 557)

15 min·theory
This chapter
3/3

@dataclass — Boilerplate Automation (PEP 557)

🎯 What you'll be able to do after this lesson

After finishing this lesson, you'll be confident doing the following 3 things.

  • ✅ @dataclass + frozen=True + slots=True options
  • ✅ Comparison with Pydantic BaseModel · NamedTuple
  • ✅ Solving the mutable default problem with field(default_factory=list)

Keep the learning objectives as a checklist, and close the lesson once you can answer all of them.

@dataclass — Code + Execution Results

@dataclass = auto-generates __init__, __repr__, __eq__. Zero boilerplate for data-holding classes.

1. Regular class vs @dataclass

python
# ❌ Old way — boilerplate
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Person(name={self.name!r}, age={self.age!r})"

    def __eq__(self, other):
        return (self.name, self.age) == (other.name, other.age)
python
# ✅ @dataclass — auto-generates the 4 methods above
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int

a = Person("Hong Gil-dong", 28)
print(a)                 # Person(name='Hong Gil-dong', age=28)  ← __repr__ auto
print(a == Person("Hong Gil-dong", 28))    # True ← __eq__ auto

2. Default values

python
@dataclass
class Person:
    name: str
    age: int = 0          # default value
    hobby: list = None       # ⚠️ list default value is a trap

a = Person("Hong Gil-dong")
print(a)                 # Person(name='Hong Gil-dong', age=0, hobby=None)

3. Immutability (frozen)

python
@dataclass(frozen=True)         # No modification
class Coordinate:
    x: float
    y: float

p = Coordinate(1.0, 2.0)
# p.x = 5.0    # FrozenInstanceError
print(hash(p))                  # Hashable → OK to use as set·dict key

4. Ordering

python
@dataclass(order=True)          # < <= > >= auto
class Score:
    value: int

a = Score(85)
b = Score(92)

5. Use field for mutable defaults

python
from dataclasses import dataclass, field

@dataclass
class Student:
    name: str
    scores: list = field(default_factory=list)    # safe empty list

a = Student("Hong Gil-dong")
a.scores.append(85)
print(a)                # Student(name='Hong Gil-dong', scores=[85])

One-line summary

A class that only holds data = always use @dataclass. PEP 557 (3.7+).

🐍 Try it yourself — dataclass — run it live

Run the concepts above as real code. The fastest way to learn is to tweak the values and observe the behavior yourself.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 Try prompting AI like this

Knowing the concepts from this lesson lets you give AI specific instructions. Instead of a vague 'fix it for me,' you make vocabulary-backed requests — and that's where token savings begin.

  • 'Convert this dict-based data structure to a dataclass'
  • 'Add __repr__ and __eq__ appropriately to this class'

Why this reduces tokens

Without the concept, even after receiving an AI answer you have to ask 'What is that?' again. That follow-up question is what eats tokens. Learn the concept once and the conversation finishes in a single round.

Read this first: Inheritance
Up next: Type Hinting
@dataclass — Boilerplate Automation (PEP 557) - Python