Python, from Zero, for AILesson 61 of 89

Module 7 · Objects, generators and the shape a larger program takes

Dataclasses: the class that is mostly data, written in four lines

In this lesson

  • 8 min read
  • 7 reading sections
  • Knowledge check
  • Lesson 2 of 10 in this chapter

This chapter’s goalRestructure a growing script into classes and dataclasses with a swappable provider behind one interface, implement the dunder methods that let your objects work with for, len, in and with, write a decorator that retries or caches, run a type checker and act on its output, make the project installable as a command with pyproject.toml, and profile it to say from measurement rather than guesswork where the time goes.

This chapter’s media

The film explains chapter ideas. The audiobook narrates the complete teaching text.

FormatEnglishहिंदी
Chapter filmWatch1:40Not available
Full audiobookNot availableNot available

A little at a time

Explore an idea, try it, then check what stays.

Step 1 of 9Free · no account needed
Lesson steps

The boilerplate

A class that mainly holds data needs the same three methods every time:

Python
class Usage:
    def __init__(self, input_tokens, output_tokens, model):
        self.input_tokens = input_tokens
        self.output_tokens = output_tokens
        self.model = model

    def __repr__(self):
        return (
            f"Usage(input_tokens={self.input_tokens!r}, "
            f"output_tokens={self.output_tokens!r}, "
            f"model={self.model!r})"
        )

    def __eq__(self, other):
        return (
            self.input_tokens,
            self.output_tokens,
            self.model,
        ) == (
            other.input_tokens,
            other.output_tokens,
            other.model,
        )

Fifteen lines, and every one of them can be derived from the three field names. dataclasses derives them:

Python
from dataclasses import dataclass

@dataclass
class Usage:
    input_tokens: int
    output_tokens: int
    model: str

Same __init__, same __repr__, same __eq__, generated at class-definition time from the annotated fields. The type annotations are what mark a line as a field; they are not checked at runtime, exactly as module 3 said of hints in general.

Python
u = Usage(2000, 500, "gpt-4o-mini")
# Usage(input_tokens=2000, output_tokens=500,
# model='gpt-4o-mini')
print(u)
print(u == Usage(2000, 500, "gpt-4o-mini"))  # True

Your place and first choices stay on this browser. Classroom credit is recorded separately.

Stuck on something?Ask Divya, your AI tutor

How to cite: Addaly (2026) ‘Dataclasses: the class that is mostly data, written in four lines’, in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/dataclasses (Accessed: 21 November 2026).