liveBook · Manning

Dataclass

As explained in Python Workout, Second Edition

A dataclass is a Python class whose commonly generated methods and field handling are supplied by the dataclass mechanism.

When class definitions repeat an __init__ method that only assigns arguments to attributes, use @dataclass to remove that boilerplate. The decorator generates __init__, comparisons, and an improved repr, leaving space for behavior you actually need to write. section 10.12

from dataclasses import dataclass

@dataclass
class Scoop():
    flavor : str

A minimal dataclass declares an annotated field at class level; the decorator turns it into an instance attribute and supplies initialization. section 10.12

Keep these implementation details in mind:

  • Annotate every dataclass attribute; annotations are mandatory there, although Python itself ignores them at runtime and external tools such as Mypy perform type checking. section 10.12
  • For collection fields, use field(default_factory=list), then add ordinary methods when the class needs behavior beyond generated methods. section 10.12

How Python Workout, Second Edition covers it

How deep it goes
Explains generated initialization, comparisons, repr, annotations, and collection-field declaration without descending into decorator internals.
Examples
Uses Scoop with a flavor field and Bowl with a list of scoops, add_scoops, and a customized repr.
What it assumes
Assumes familiarity with Python classes, attributes, methods, and type annotations while clarifying dataclass-specific annotation requirements.
What you can do after
Build dataclasses with generated initialization and explicitly annotated fields, then extend them with ordinary methods.
How it connects
Connects classes, instance attributes, type annotations, external type checking, and custom methods.

Also explained in

Compare how 7 books explain dataclass →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.