When an application models clear data objects such as units, quantities, results, or haikus, a dataclass keeps the class definition short while supplying standard basic functionality. The dataclasses module is part of Python’s standard library. section 3.6.2 section 8.5.1
A dataclass provides a practical structure for data-focused classes:
- Add the @dataclass decorator above the class definition. section 3.6.2
- Declare fields with type annotations such as abbrev: str or value_in_std_units: float. section 3.6.2
- Instantiate the class without writing a __init__ method, then access fields with dot notation. section 3.6.2
- Use separate dataclasses when related data has distinct responsibilities, such as Unit, Quantity, and Result. section 3.6.2
A unit conversion object
from dataclasses import dataclass @dataclass class Unit: abbrev: str value_in_std_units: float gram = Unit(abbrev="g", value_in_std_units=0.001) print(gram.abbrev) # Prints 'g' The dataclass replaces the longer regular-class version that manually assigns both attributes in __init__. section 3.6.2
Representing database records
A dataclass can mirror a database table’s returned fields. Haiku contains haiku_id, created_at, author, and text, allowing a service to return Haiku(*results[0]) after inserting a record. section 8.5.1
Listing 3.2 The Unit dataclass in unit.py
from dataclasses import dataclass
@dataclass
class Unit:
abbrev: str
value_in_std_units: float
Inspect the complete Unit declaration and its two typed fields. section 3.6.2
Listing 8.14 The Haiku dataclass
from dataclasses import dataclass
@dataclass
class Haiku:
haiku_id: int
created_at: str
author: str
text: str
Compare a dataclass used as a backend representation of a persisted record. section 8.5.1






