{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"dataclasses","title":"Dataclasses: the class that is mostly data, written in four lines","url":"https://addaly.com/learn/python-for-ai/dataclasses","position":61,"of":89,"minutes":8,"answer":"A dataclass writes __init__, __repr__ and __eq__ from the field list; a mutable default must go through field(default_factory=...), frozen=True makes instances hashable and immutable, and asdict is the road to JSON.","keyIdea":"A dataclass writes __init__, __repr__ and __eq__ from the field list; a mutable default must go through field(default_factory=...), frozen=True makes instances hashable and immutable, and asdict is the road to JSON."},"body":{"format":"markdown","text":"## The boilerplate\n\nA class that mainly holds data needs the same three methods every time:\n\n```python\nclass Usage:\n    def __init__(self, input_tokens, output_tokens, model):\n        self.input_tokens = input_tokens\n        self.output_tokens = output_tokens\n        self.model = model\n\n    def __repr__(self):\n        return (\n            f\"Usage(input_tokens={self.input_tokens!r}, \"\n            f\"output_tokens={self.output_tokens!r}, \"\n            f\"model={self.model!r})\"\n        )\n\n    def __eq__(self, other):\n        return (\n            self.input_tokens,\n            self.output_tokens,\n            self.model,\n        ) == (\n            other.input_tokens,\n            other.output_tokens,\n            other.model,\n        )\n```\n\nFifteen lines, and every one of them can be derived from the three field names. `dataclasses` derives them:\n\n```python\nfrom dataclasses import dataclass\n\n@dataclass\nclass Usage:\n    input_tokens: int\n    output_tokens: int\n    model: str\n```\n\nSame `__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.\n\n```python\nu = Usage(2000, 500, \"gpt-4o-mini\")\n# Usage(input_tokens=2000, output_tokens=500,\n# model='gpt-4o-mini')\nprint(u)\nprint(u == Usage(2000, 500, \"gpt-4o-mini\"))  # True\n```\n\nYou can still add methods. A dataclass is an ordinary class with some methods written for you:\n\n```python\n    def cost(self, prices):\n        p = prices[self.model]\n        return (\n            self.input_tokens * p[\"in\"]\n            + self.output_tokens * p[\"out\"]\n        ) / 1e6\n```\n\n## Defaults, and the mutable one\n\nFields with defaults go after fields without, as with function arguments:\n\n```python\n@dataclass\nclass Job:\n    model: str\n    max_tokens: int = 500\n    temperature: float = 0.0\n```\n\nNow the list:\n\n```python\n@dataclass\nclass Job:\n    model: str\n    prompts: list[str] = []        # ValueError at class definition\n```\n\nThe dataclass refuses. It is protecting you from the shared-list trap of the previous lesson: `[]` evaluated once at definition time would become the default for every instance. The fix is a factory, a function called once per instance:\n\n```python\nfrom dataclasses import field\n\n@dataclass\nclass Job:\n    model: str\n    prompts: list[str] = field(default_factory=list)\n    options: dict = field(default_factory=dict)\n```\n\n`default_factory=list` calls `list()` for each new `Job`. Any zero-argument callable works, including a lambda that builds something more elaborate.\n\n## Frozen\n\n```python\n@dataclass(frozen=True)\nclass ModelSpec:\n    name: str\n    context_window: int\n    price_in: float\n    price_out: float\n```\n\nAssigning to a field of a frozen instance raises `FrozenInstanceError`. Two things follow. A frozen dataclass is **hashable**, so it can be a dict key or a set member: a useful property for a cache keyed on `(model, prompt)`. And it is safe to share: a function that receives a `ModelSpec` cannot accidentally change it for everyone else.\n\nConfiguration objects want to be frozen. Anything that is a record of a fact (a usage figure, a price at a date) wants to be frozen. Things that change over their life, like a `Conversation`, do not.\n\n## Ordering and other options\n\n`@dataclass(order=True)` generates `<`, `<=` and the rest, comparing field by field in declaration order, so a list of instances sorts without a `key`. `kw_only=True` makes every field keyword-only, which prevents the bug where two `int` fields get swapped by position. `slots=True` stores fields in a fixed structure instead of a per-instance dict, which halves memory for a million small objects and makes attribute access slightly faster.\n\n## To and from dicts\n\n```python\nfrom dataclasses import asdict\n\njson.dumps(asdict(u))                  # '{\"input_tokens\": 2000, ...}'\nUsage(**json.loads(text))              # back again\n```\n\n`asdict` recurses into nested dataclasses, lists and dicts. The `**` unpacking on the way back works as long as the JSON keys match the field names exactly and nothing extra is present; an unexpected key raises `TypeError`. That strictness is a feature when reading your own files, and a nuisance when reading someone else's, which is where the next paragraph comes in.\n\n## When to reach for pydantic instead\n\nA dataclass trusts its inputs. `Usage(\"2000\", None, 42)` constructs happily; the types are decoration. When the data comes from outside (a file someone else wrote, a model's reply, a web request) you want validation, and that is pydantic's `BaseModel`, which you met in module 6. It looks almost identical:\n\n```python\nclass Usage(BaseModel):\n    input_tokens: int\n    output_tokens: int\n    model: str\n```\n\nbut `Usage(input_tokens=\"2000\", ...)` coerces to `2000`, and `Usage(input_tokens=\"lots\", ...)` raises with a message. The rule: dataclasses for your own internal objects, pydantic at the boundary where untrusted data enters. Do not put pydantic on everything; validation costs time, and inside your own code the types are already right.\n\n`NamedTuple` is a third option (a tuple with names, immutable, hashable, unpackable) and is the lightest of the three when a function needs to return two or three values with names. `TypedDict` is a fourth: it is a dict with declared keys, for when the data must stay a dict because a library wants one.\n\n## Try this now\n\nTurn the `Budget` class from module 6 into a dataclass with `cap_usd: float`, `spent: float = 0.0` and `calls: int = 0`, keeping the `charge` method. Then make a frozen `ModelSpec`, put two of them in a set, and try to change one."},"check":{"question":"A developer declares `@dataclass class Job: prompts: list = []` and Python refuses to define the class with `ValueError: mutable default <class 'list'> for field prompts is not allowed`. What is the dataclass protecting them from?","options":[{"text":"The shared-list trap: one list made at definition time would be every instance's default, so the dataclass insists on a factory that builds a fresh one.","correct":true},{"text":"Lists cannot be type-annotated without a type parameter, so `list[str]` would have been accepted where `list` was not.","correct":false,"tempting":"The annotation is fine; the error is about the default value, and `list[str] = []` fails identically."},{"text":"Dataclass fields must be immutable so that instances can be used as dictionary keys and set members, which a list field would prevent, so the decorator rejects any mutable type at definition.","correct":false,"tempting":"Only `frozen=True` dataclasses are hashable, and even those may contain list fields; the restriction is on the default, not the type."},{"text":"An empty list default makes `__eq__` ambiguous, because two instances with empty lists would compare equal.","correct":false,"tempting":"Two instances with equal fields comparing equal is exactly what a dataclass is meant to do; it is not the error."}]},"prev":{"slug":"classes-and-objects","title":"Classes: when a dict stops being enough","url":"https://addaly.com/learn/python-for-ai/classes-and-objects"},"next":{"slug":"inheritance-and-composition","title":"Inheritance and composition: swapping one model provider for another","url":"https://addaly.com/learn/python-for-ai/inheritance-and-composition"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"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).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Dataclasses: the class that is mostly data, written in four lines","courseTitle":"Python, from Zero, for AI","module":{"index":7,"slug":"objects-and-the-shape-of-programs","title":"Objects, generators and the shape a larger program takes"},"answer":null,"keyIdea":"A dataclass writes __init__, __repr__ and __eq__ from the field list; a mutable default must go through field(default_factory=...), frozen=True makes instances hashable and immutable, and asdict is the road to JSON.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"the-boilerplate","runs":[{"text":"The boilerplate"}]},{"t":"p","runs":[{"text":"A class that mainly holds data needs the same three methods every time:"}]},{"t":"code","lang":"python","label":"Python","text":"class Usage:\n    def __init__(self, input_tokens, output_tokens, model):\n        self.input_tokens = input_tokens\n        self.output_tokens = output_tokens\n        self.model = model\n\n    def __repr__(self):\n        return (\n            f\"Usage(input_tokens={self.input_tokens!r}, \"\n            f\"output_tokens={self.output_tokens!r}, \"\n            f\"model={self.model!r})\"\n        )\n\n    def __eq__(self, other):\n        return (\n            self.input_tokens,\n            self.output_tokens,\n            self.model,\n        ) == (\n            other.input_tokens,\n            other.output_tokens,\n            other.model,\n        )"},{"t":"p","runs":[{"text":"Fifteen lines, and every one of them can be derived from the three field names. "},{"text":"dataclasses","code":true},{"text":" derives them:"}]},{"t":"code","lang":"python","label":"Python","text":"from dataclasses import dataclass\n\n@dataclass\nclass Usage:\n    input_tokens: int\n    output_tokens: int\n    model: str"},{"t":"p","runs":[{"text":"Same "},{"text":"__init__","code":true},{"text":", same "},{"text":"__repr__","code":true},{"text":", same "},{"text":"__eq__","code":true},{"text":", 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."}]},{"t":"code","lang":"python","label":"Python","text":"u = Usage(2000, 500, \"gpt-4o-mini\")\n# Usage(input_tokens=2000, output_tokens=500,\n# model='gpt-4o-mini')\nprint(u)\nprint(u == Usage(2000, 500, \"gpt-4o-mini\"))  # True"},{"t":"p","runs":[{"text":"You can still add methods. A dataclass is an ordinary class with some methods written for you:"}]},{"t":"code","lang":"python","label":"Python","text":"    def cost(self, prices):\n        p = prices[self.model]\n        return (\n            self.input_tokens * p[\"in\"]\n            + self.output_tokens * p[\"out\"]\n        ) / 1e6"},{"t":"h2","id":"defaults-and-the-mutable-one","runs":[{"text":"Defaults, and the mutable one"}]},{"t":"p","runs":[{"text":"Fields with defaults go after fields without, as with function arguments:"}]},{"t":"code","lang":"python","label":"Python","text":"@dataclass\nclass Job:\n    model: str\n    max_tokens: int = 500\n    temperature: float = 0.0"},{"t":"p","runs":[{"text":"Now the list:"}]},{"t":"code","lang":"python","label":"Python","text":"@dataclass\nclass Job:\n    model: str\n    prompts: list[str] = []        # ValueError at class definition"},{"t":"p","runs":[{"text":"The dataclass refuses. It is protecting you from the shared-list trap of the previous lesson: "},{"text":"[]","code":true},{"text":" evaluated once at definition time would become the default for every instance. The fix is a factory, a function called once per instance:"}]},{"t":"code","lang":"python","label":"Python","text":"from dataclasses import field\n\n@dataclass\nclass Job:\n    model: str\n    prompts: list[str] = field(default_factory=list)\n    options: dict = field(default_factory=dict)"},{"t":"p","runs":[{"text":"default_factory=list","code":true},{"text":" calls "},{"text":"list()","code":true},{"text":" for each new "},{"text":"Job","code":true},{"text":". Any zero-argument callable works, including a lambda that builds something more elaborate."}]},{"t":"h2","id":"frozen","runs":[{"text":"Frozen"}]},{"t":"code","lang":"python","label":"Python","text":"@dataclass(frozen=True)\nclass ModelSpec:\n    name: str\n    context_window: int\n    price_in: float\n    price_out: float"},{"t":"p","runs":[{"text":"Assigning to a field of a frozen instance raises "},{"text":"FrozenInstanceError","code":true},{"text":". Two things follow. A frozen dataclass is "},{"text":"hashable","b":true},{"text":", so it can be a dict key or a set member: a useful property for a cache keyed on "},{"text":"(model, prompt)","code":true},{"text":". And it is safe to share: a function that receives a "},{"text":"ModelSpec","code":true},{"text":" cannot accidentally change it for everyone else."}]},{"t":"p","runs":[{"text":"Configuration objects want to be frozen. Anything that is a record of a fact (a usage figure, a price at a date) wants to be frozen. Things that change over their life, like a "},{"text":"Conversation","code":true},{"text":", do not."}]},{"t":"h2","id":"ordering-and-other-options","runs":[{"text":"Ordering and other options"}]},{"t":"p","runs":[{"text":"@dataclass(order=True)","code":true},{"text":" generates "},{"text":"<","code":true},{"text":", "},{"text":"<=","code":true},{"text":" and the rest, comparing field by field in declaration order, so a list of instances sorts without a "},{"text":"key","code":true},{"text":". "},{"text":"kw_only=True","code":true},{"text":" makes every field keyword-only, which prevents the bug where two "},{"text":"int","code":true},{"text":" fields get swapped by position. "},{"text":"slots=True","code":true},{"text":" stores fields in a fixed structure instead of a per-instance dict, which halves memory for a million small objects and makes attribute access slightly faster."}]},{"t":"h2","id":"to-and-from-dicts","runs":[{"text":"To and from dicts"}]},{"t":"code","lang":"python","label":"Python","text":"from dataclasses import asdict\n\njson.dumps(asdict(u))                  # '{\"input_tokens\": 2000, ...}'\nUsage(**json.loads(text))              # back again"},{"t":"p","runs":[{"text":"asdict","code":true},{"text":" recurses into nested dataclasses, lists and dicts. The "},{"text":"**","code":true},{"text":" unpacking on the way back works as long as the JSON keys match the field names exactly and nothing extra is present; an unexpected key raises "},{"text":"TypeError","code":true},{"text":". That strictness is a feature when reading your own files, and a nuisance when reading someone else’s, which is where the next paragraph comes in."}]},{"t":"h2","id":"when-to-reach-for-pydantic-instead","runs":[{"text":"When to reach for pydantic instead"}]},{"t":"p","runs":[{"text":"A dataclass trusts its inputs. "},{"text":"Usage(\"2000\", None, 42)","code":true},{"text":" constructs happily; the types are decoration. When the data comes from outside (a file someone else wrote, a model’s reply, a web request) you want validation, and that is pydantic’s "},{"text":"BaseModel","code":true},{"text":", which you met in module 6. It looks almost identical:"}]},{"t":"code","lang":"python","label":"Python","text":"class Usage(BaseModel):\n    input_tokens: int\n    output_tokens: int\n    model: str"},{"t":"p","runs":[{"text":"but "},{"text":"Usage(input_tokens=\"2000\", ...)","code":true},{"text":" coerces to "},{"text":"2000","code":true},{"text":", and "},{"text":"Usage(input_tokens=\"lots\", ...)","code":true},{"text":" raises with a message. The rule: dataclasses for your own internal objects, pydantic at the boundary where untrusted data enters. Do not put pydantic on everything; validation costs time, and inside your own code the types are already right."}]},{"t":"p","runs":[{"text":"NamedTuple","code":true},{"text":" is a third option (a tuple with names, immutable, hashable, unpackable) and is the lightest of the three when a function needs to return two or three values with names. "},{"text":"TypedDict","code":true},{"text":" is a fourth: it is a dict with declared keys, for when the data must stay a dict because a library wants one."}]},{"t":"h2","id":"try-this-now","runs":[{"text":"Try this now"}],"role":"try"},{"t":"p","runs":[{"text":"Turn the "},{"text":"Budget","code":true},{"text":" class from module 6 into a dataclass with "},{"text":"cap_usd: float","code":true},{"text":", "},{"text":"spent: float = 0.0","code":true},{"text":" and "},{"text":"calls: int = 0","code":true},{"text":", keeping the "},{"text":"charge","code":true},{"text":" method. Then make a frozen "},{"text":"ModelSpec","code":true},{"text":", put two of them in a set, and try to change one."}]}],"check":{"question":[{"text":"A developer declares "},{"text":"@dataclass class Job: prompts: list = []","code":true},{"text":" and Python refuses to define the class with "},{"text":"ValueError: mutable default <class 'list'> for field prompts is not allowed","code":true},{"text":". What is the dataclass protecting them from?"}],"options":[{"text":[{"text":"The shared-list trap: one list made at definition time would be every instance’s default, so the dataclass insists on a factory that builds a fresh one."}],"correct":true,"tempting":null},{"text":[{"text":"Lists cannot be type-annotated without a type parameter, so "},{"text":"list[str]","code":true},{"text":" would have been accepted where "},{"text":"list","code":true},{"text":" was not."}],"correct":false,"tempting":[{"text":"The annotation is fine; the error is about the default value, and "},{"text":"list[str] = []","code":true},{"text":" fails identically."}]},{"text":[{"text":"Dataclass fields must be immutable so that instances can be used as dictionary keys and set members, which a list field would prevent, so the decorator rejects any mutable type at definition."}],"correct":false,"tempting":[{"text":"Only "},{"text":"frozen=True","code":true},{"text":" dataclasses are hashable, and even those may contain list fields; the restriction is on the default, not the type."}]},{"text":[{"text":"An empty list default makes "},{"text":"__eq__","code":true},{"text":" ambiguous, because two instances with empty lists would compare equal."}],"correct":false,"tempting":[{"text":"Two instances with equal fields comparing equal is exactly what a dataclass is meant to do; it is not the error."}]}],"order":[1,3,2,0],"why":null},"prev":{"slug":"classes-and-objects","title":"Classes: when a dict stops being enough","minutes":9},"next":{"slug":"inheritance-and-composition","title":"Inheritance and composition: swapping one model provider for another","minutes":9}}}