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
2. Default values
3. Immutability (frozen)
4. Ordering
5. Use field for mutable defaults
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