Skip to main content
Module 9 · Lesson 2 of 434/36 in the course~16 min
Module lessons (2/4)

dataclass: data classes without boilerplate

Lesson preview5 hands-on exercises readyPython Course · Module 9 — Modern Python in practice

@dataclass, field(default_factory=...), frozen=True, and generated __init__/__repr__/__eq__.

What you'll learn in this lesson

  • Eliminate the repetitive boilerplate of __init__, __repr__ and __eq__ with the @dataclass decorator.
  • Configure fields with securely mutable defaults via field(default_factory=list).
  • Create immutable and hashable value-objects using @dataclass(frozen=True).
  • Validate or calculate derived fields immediately after initialization with __post_init__.

Overview

When you write a class that is primarily used to hold structured data, repeating __init__, __repr__, and __eq__ by hand makes the code cumbersome and introduces distracting errors. The standard module dataclasses reads the type annotations of the class and automatically generates these dunder methods for you.

Unlike namedtuple (which is always immutable and derives from tuple), @dataclass generates real Python classes that you can extend with custom methods, optional fields, and selective immutability.

Sections covered in this lesson

  1. 11. Complete data class in a few lines
  2. 22. Safe mutable defaults with field(default_factory=...)
  3. 33. Immutable and hashable objects with frozen=True
  4. 44. Validation and derived fields in __post_init__
  5. 5Check for understanding
  6. 6Test yourself
Pro Lesson · Module 9 — Modern Python in practice

Unlock "dataclass: data classes without boilerplate" and the full Python Course curriculum

@dataclass, field(default_factory=...), frozen=True, and generated __init__/__repr__/__eq__.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Python Course plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.