liveBook · Manning

Dataclass

As explained in Python Workout: 50 ten-minute exercises

dataclass is a Python standard-library decorator that generates class boilerplate such as an initializer, representations, and comparison methods from declared fields.

When a class mostly stores data, its __init__ method can repeat the same assignment boilerplate. The @dataclass decorator generates that initializer, comparisons, and an improved __repr__, letting the class focus on its useful behavior. section 9.10

A minimal data class

@dataclass class Scoop: flavor: str The flavor annotation declares the field; the decorator creates the initializer and other class methods. Data-class attributes require type annotations, although Python itself does not enforce their types. section 9.10

A mutable collection field

from dataclasses import dataclass, field @dataclass class Bowl: scoops: list = field(default_factory=list) def add_scoops(self, *new_scoops): for scoop in new_scoops: self.scoops.append(scoop) This combines generated construction with an explicit method for changing the collection.

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains generated initializers, comparisons, representations, and mandatory annotations, but not decorator implementation internals.
Examples
Uses Scoop and Bowl classes, including a typed flavor field and a default-created collection of scoops.
What it assumes
Assumes familiarity with classes and teaches that data-class fields require annotations while type checking remains external.
What you can do after
Apply it via the @dataclass decorator to replace routine initializer and representation code.
How it connects
Connects classes with type annotations, external type checking, comparisons, and object representations.

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: 50 ten-minute exercises. The section links point to the parts of the book it draws on.