Dataclasses and Named Tuples
What you'll build
A data model for a book store using @dataclass for mutable Book and NamedTuple for immutable ISBN, with validation and serialization.
Goals
- Define a dataclass with type hints and defaults
- Use field() for mutable defaults like lists
- Create an immutable NamedTuple
- Add methods and serialization to dataclasses
Prerequisites
- Classes and __init__
- Type hints (basic)
- Dictionaries
Steps
- 1
Define a Book dataclass
@dataclass auto-generates __init__, __repr__, and __eq__ from your type-annotated fields. Write a Book with title, author, price, and tags.
Codefrom dataclasses import dataclass, field @dataclass class Book: title: str author: str price: float tags: list = field(default_factory=list) b1 = Book("Python 101", "Alice", 29.99, ["programming", "python"]) b2 = Book("Python 101", "Alice", 29.99, ["programming", "python"]) print(b1) # auto __repr__ print(b1 == b2) # True — auto __eq__Expected result
Books print nicely and compare by value, not identity.
- 2
Use field for mutable defaults
Never use a mutable default like tags=[] — all instances would share the same list. Use field(default_factory=list) to create a fresh list per instance.
Hint
This is the same reason you use def f(x=None): x = x or [] in functions.
- 3
Make a frozen dataclass
Add frozen=True to make the dataclass immutable (like a NamedTuple). Attempting to set a field raises FrozenInstanceError. Useful for hashable, safe data.
Hint
Frozen dataclasses are hashable and can be used as dict keys or set members.
- 4
Define an ISBN NamedTuple
NamedTuple is immutable and memory-efficient. Define an ISBN with group, publisher, title, and check_digit fields, and a method to format the full string.
Codefrom typing import NamedTuple class ISBN(NamedTuple): group: int publisher: int title: int check_digit: int def __str__(self): return f"{self.group}-{self.publisher}-{self.title}-{self.check_digit}" isbn = ISBN(978, 316, 152410, 17) print(isbn) # 978-316-152410-17 print(isbn.publisher) # 316 — field access by nameExpected result
ISBN prints as a formatted string and fields are accessible by name.
- 5
Add serialization
Use dataclasses.asdict to convert a dataclass to a dict, and **kwargs to construct from a dict. This is the basis for JSON serialization.
Codefrom dataclasses import asdict book = Book("Deep Work", "Cal Newport", 18.50, ["productivity"]) d = asdict(book) print(d) # {'title': 'Deep Work', 'author': 'Cal Newport', 'price': 18.5, 'tags': ['productivity']} # Reconstruct from dict book2 = Book(**d) print(book2 == book) # TrueExpected result
Round-trip: dataclass → dict → dataclass preserves equality.
Try it yourself
from dataclasses import dataclass
@dataclass
class Book:
# TODO: fields
pass@dataclass
class Book:
title: str; author: str; price: float; tags: list = field(default_factory=list)What you learned
You used dataclasses and NamedTuples to model data with minimal boilerplate — they're the modern Python way to structure data, replacing verbose __init__ methods.
Related Resources
Related Lessons
- Classes
Dataclasses are concise class definitions.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.