liveBook · Manning

Dataclass

As explained in Build Python Web Apps with Streamlit

A dataclass is a Python class form that automatically supplies standard methods and supports concise declaration of data fields.

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

How Build Python Web Apps with Streamlit covers it

How deep it goes
Explains decoration, fields, annotations, initialization, and attribute access, but does not detail generated methods beyond __init__.
Examples
Uses Unit, Quantity, Result, and Haiku classes to model conversion data and persisted haiku records.
What it assumes
Assumes basic Python classes and attributes while introducing decorators, type annotations, and dataclasses from practical examples.
What you can do after
Build it from scratch as a concise typed class for application data and access its fields with dot notation.
How it connects
Connects dataclasses with type annotations, classes, standard-library modules, database records, and service-layer design.

Also explained in

Compare how 7 books explain dataclass →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Python Web Apps with Streamlit. The section links point to the parts of the book it draws on.