Python Dataclasses in Practice: Stop Passing Dicts Around
AI-generated Python is full of dicts, and a misspelled field name only fails at runtime with a KeyError. One dataclass decorator generates the constructor, repr, and equality — a typo shows up immediately. This guide demos with 8 tasks: 600 minutes, 465 done, 135 pending, covering defaults, validation, frozen, ordering, JSON round-trip, and slots. Python 3.12.3.

The most common shape in AI-generated Python code is a screen full of dictionaries: a task is {"name": "Draft", "minutes": 120, "done": True}, you read values with task["minutes"], and everything passes around by convention. When the convention changes — someone writes mins instead of minutes — the program does not fail where the data is defined. It fails somewhere in a corner with a KeyError, and you trace the call chain to find it. Data classes exist to fix exactly this: one decorator, you write the field names and types, and Python generates the constructor, the printable representation, and the equality comparison for you. A misspelled field name shows up immediately. This guide uses a fictional "tasks this week" tracker as the demo: 8 tasks, 600 estimated minutes, 5 done for 465 minutes, 3 pending for 135 minutes, the longest being "Demo" at 180 minutes. Every number comes from the demo script demo247_zh.py actually running; the English rerun is rerun_en_demo247_g2.py, and both runs agree. The local environment is Python 3.12.3, data classes are the standard library dataclasses module, zero third-party packages.
One thing up front: a data class is not a new idea. It just hands the boilerplate you would have written anyway to Python. Without it, a class needs an __init__ that takes parameters and assigns them one by one to self, then a __repr__ for debugging, then an __eq__ for comparison — three blocks, twenty or thirty lines, easy to get wrong. A data class deletes all three: you write the fields, the decorator does the rest. The Python docs put it plainly: this module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes, and the fields are defined with type annotations. Understand that one sentence and everything below follows naturally.
From dict to data class: three blocks less, three things more
Section 1 of the demo defines a Task data class with 5 fields: name, estimated minutes, done flag, tag list, and priority. done defaults to False, priority defaults to 3, and only name and minutes are required. Write the decorator and the fields, and three things appear automatically. First, the constructor: Task("Draft", 120, True, ["writing"], 2) builds a task, with parameters in the order the fields are defined — the docs state that the order of the fields in all of the generated methods is the order in which they appear in the class definition. Second, the printable representation: printing the first task gives Task(name='Draft', minutes=120, done=True, tags=['writing'], priority=2), class name, field names, and values all in one line, readable at a glance while debugging, with no string formatting of your own.
Third, equality: two tasks with the same content are equal. Section 3 of the demo builds a fresh task with exactly the same content as the first one and compares them: True. Compare it with the second task and the result is False. Dicts do compare equal by content too — that is not the point. The point is spelling: task["minute"] with a letter missing only fails at runtime with a KeyError; task.minute gets flagged by your editor before the program runs. Misspelled field names are one of the most common defects in AI-generated code, and data classes move that defect from runtime to write time. That is their main value.
The 8 demo tasks are worth recording here in full: Draft 120 minutes, Diagram 90, Demo 180, Tests 60, Proofread 45, Cover 30, Publish check 25, Replies 50 — 600 minutes in total. The 5 done tasks are Draft, Diagram, Demo, Proofread, and Cover, 465 minutes together; the 3 pending ones are Tests, Publish check, and Replies, 135 minutes together. 465 plus 135 is exactly 600. You can match each number against the demo transcript, or change the numbers and run the script again — the demo is built for that.
Defaults and mutable defaults: one copy per instance
Section 2 of the demo covers the easiest data-class trap: mutable defaults. The old Python rule is that a function default is evaluated once, at definition time, and shared by every call — a list as a default is the classic trap, with two instances mutating the same list. Data classes follow the same rule but offer the correct spelling: field(default_factory=list), which means call list() fresh every time a new instance is built, one new empty list per instance. In the demo, two tasks are built without tags; after appending "urgent" to task A's tags, the counts are: task A has 1 tag, task B has 0, and a.tags is b.tags is False — proof they are not the same list.
The docs describe this spelling directly: if a field's default is specified by a call to field(), the default_factory is a zero-argument callable that is called when a default value is needed, and one of its purposes is specifying fields with mutable default values. Write tags: list = [] instead, and the data class refuses outright. That refusal is a favor: it turns a ghost bug at runtime into a clear error at definition time. AI-generated code frequently contains tags: list = []; it looks harmless when pasted, then two instances' tags leak into each other and the bug takes a while to find. Remember the rule: if a field default is a list, dict, or set, always use field(default_factory=...).
Immutable defaults need none of this: done: bool = False and priority: int = 3 are written directly, because booleans and integers cannot be mutated in place. One more ordering rule: a field without a default cannot follow a field with a default, or you get a TypeError. That is because the generated constructor puts parameters with defaults last — the same rule as plain function definitions, inherited by data classes. The demo's Task is ordered that way: name and minutes first, the three fields with defaults after.
__post_init__: validation inside the constructor
Data classes generate the constructor, but validation logic is still yours to write, and the place to write it is __post_init__: the generated __init__ calls it automatically after assigning every field. Section 4 of the demo puts two checks there: estimated minutes must be greater than 0, and priority must be between 1 and 5. The demo deliberately builds two bad tasks: minutes=0 raises ValueError: minutes must be greater than 0, got 0, and priority=9 raises ValueError: priority must be between 1 and 5, got 9. Both are caught by try and printed, and the transcript has the exact messages.
Why validate in the constructor instead of checking later when the data is used? Because once an instance is built, it is valid by construction, and every piece of code that uses it can stop doubting it. If validation is scattered around, every place that uses a task has to ask "are the minutes positive?" first, and one missed question can produce a negative total. __post_init__ exists for exactly this: run checks — and compute derived fields, such as hours from minutes, or strip whitespace from a name — in the first moment after construction. One thing to note: inside __post_init__ you can only use fields that have already been assigned, because it runs after __init__ has assigned them all, and that order is guaranteed.
A word on the exception type: raising ValueError is the Python convention for "the value itself is invalid", as opposed to TypeError for "the type is wrong". In the demo, minutes of 0 is a value problem, hence ValueError; pass a string as minutes and the data class will not stop you, because data classes do not enforce types at runtime — annotations are annotations, not runtime checks. That is also the difference between data classes and a validation library like Pydantic: data classes handle structure, not type enforcement, and scenarios that need strict type validation still need another tool. The closing boundaries section returns to this.
frozen: configuration that cannot be changed
Section 5 of the demo defines a frozen data class, Config, with two fields: the name defaults to "Morning Reading" and the daily minute cap defaults to 240. Build it, then try to change it: cfg.max_minutes_per_day = 300 raises FrozenInstanceError: cannot assign to field 'max_minutes_per_day'. It cannot be changed. Frozen means read-only: once an instance is built, its fields are locked. That fits configuration best: a daily cap of 240 minutes, a project name — values that should not change after the program starts. Anyone who changes them has a bug, and freezing exposes that bug at the moment of the change instead of when the wrong result is computed.
Freezing has a connected benefit, to do with hashing. The docs spell out the rule for generating __hash__: when eq and frozen are both true, a __hash__ method is generated by default; when eq is true but frozen is false, __hash__ is set to None and instances cannot go into sets or be used as dictionary keys. The reasoning is simple: anything in a set must keep a stable hash, and a mutable instance's hash can change at any time — putting it in a set is asking for trouble. The demo's Task is not frozen, so it cannot be hashed; the demo's Config is frozen, so it can. You do not need to memorize the rule, just the conclusion: if you want instances in sets or as dict keys, freeze them.
Freezing is not free: a frozen instance cannot assign to its own fields inside __post_init__, because assignment itself is the forbidden operation, and derived fields in a frozen class need the awkward object.__setattr__ workaround. So the principle is: freeze things that are built and then never change — configuration, coordinates, records; do not freeze things whose state changes, like tasks and orders. The demo's Task.done has to flip from False to True when work is finished, and freezing would make that impossible.
order=True: sorting for free
Section 6 of the demo adds order=True to a data class called Deadline: two fields, date first, name second. With that parameter, the data class generates the four comparison methods __lt__, __le__, __gt__, and __ge__, comparing field by field in order, just like comparing tuples. The demo's 4 deadlines are given out of order — 2026-11-20 Publish check, 2026-11-18 Demo, 2026-11-25 Replies, 2026-11-15 Draft — and after sorting they come out as 2026-11-15 Draft, 2026-11-18 Demo, 2026-11-20 Publish check, 2026-11-25 Replies. The earliest deadline is 2026-11-15 (Draft).
One detail deserves attention: comparison only looks at the earlier fields. If two deadlines share a date, only then does the name get compared; with different dates, the name never matters. So field order is the sort order: put the field you most want to sort by first. To sort by priority, put the priority field first — or skip order=True entirely and write sorted(tasks, key=lambda t: t.priority). Section 1 of the demo finds the longest task exactly that way: max(TASKS, key=lambda t: t.minutes) returns "Demo" at 180 minutes. Both spellings are right: order=True fits classes that have a natural order, like deadlines; key fits "sort by this today, by that tomorrow".
One more constraint: order=True requires eq=True, or it raises a ValueError. The logic is straightforward: anything that can be ordered must at least be comparable for equality, or "equal" and "less than" would contradict each other. The default for eq is already True, so you will rarely hit this error unless you turn eq off by hand. If you do, give up on sorting and write a key function instead.
asdict and JSON: a full round-trip
Section 7 of the demo does the save-and-load loop: turn the 8 tasks into a list of dicts, then into a JSON string, parse it back, and rebuild the tasks, checking that nothing changed. The result: 8 tasks after the JSON round-trip, 600 total minutes, and the round-trip content is identical to the original: True. The tool used is asdict, the data-class helper that recursively converts an instance to a dict — nested data classes, lists, and dicts are converted layer by layer — producing something json.dumps accepts directly. There is no built-in reverse function; you write it yourself in one line: [Task(**d) for d in json.loads(blob)], unpacking each dict into constructor arguments.
This round-trip deserves its own section because it is the most common data flow in vibe projects: objects in the program, JSON on disk, objects again when loaded. The dict version's problem is that a loaded dict has no type — a misspelled field name only fails when the value is used. The data-class version loads back into real Task instances: a wrong field name fails at construction, and the __post_init__ checks run again, so data that was valid when saved is still valid when loaded. The file-I/O guide on this site already covers reading and writing JSON; this guide adds the second half: do not stop at dicts after loading — turn them back into data classes, and the rest of the code gets types and validation as a safety net.
One trap to state in advance: asdict cannot convert dates on its own, and json.dumps raises an error on a date object. The demo's Task has no date field, so this did not trigger; the demo's Deadline has a date, but that section never goes through JSON. If your own data class has dates, convert them to strings first — isoformat() on the way out, date.fromisoformat() on the way back in. A related point: asdict deep-copies mutable fields, so editing the resulting dict does not affect the original instance — the docs say so explicitly, and you can rely on it.
The chart above shows the estimated minutes for the 8 tasks, and the numbers match the demo transcript exactly. The takeaway at a glance: "Demo" alone takes 180 minutes, one and a half times the runner-up "Draft" at 120, while the 3 pending tasks add up to only 135 minutes — most of the work is already done. Blue is the 5 done tasks, 465 minutes; orange is the 3 pending tasks, 135 minutes; the colors alone make the progress clear. That is another benefit of writing tasks as data classes: to see the distribution, one summation plus one chart, instead of counting through dicts by hand.
slots=True: blocking misspelled attribute names
Section 8 of the demo is the last feature: slots=True. A Point is defined with two fields, x and y; building it and then trying to add a new attribute, p.z = 3.0, raises AttributeError: 'Point' object has no attribute 'z'. It cannot be added. Ordinary class instances carry a dict behind them, and any attribute can be stuffed in — a misspelled attribute name quietly moves in, for example assigning to point.xx when you meant point.x: the assignment succeeds, but reads still return the old value, and the bug takes a while to find. With slots on, the instance has no such dict; only declared fields exist, and a misspelled attribute fails at the moment of assignment.
slots also saves memory — each instance drops a dict, which adds up when there are tens of thousands of instances — but for vibe projects that is secondary; blocking misspelled attributes is the real win. The docs describe slots like this: when true, a __slots__ attribute is generated and a new class is returned instead of the original one; the parameter was added in Python 3.10. One constraint to remember: if the class already defines __slots__, passing slots=True raises a TypeError — pick one or the other. The demo's Point is the simplest possible use, which is enough; for trickier inheritance cases, the docs have the details.
One more note: slots=True and frozen=True can be combined — one blocks new attributes, the other blocks changing existing fields — and together they make a fully locked-down little object, suitable as a dict key or a set member. The demo does not combine them, because Config already covered freezing and Point only covers slots; keeping them separate is clearer, and combining them is just a matter of passing both parameters.
Three uses you can copy directly
Now three uses that fit the most common vibe projects, ready to copy. First, configuration objects: every project has a pile of settings — a daily minute cap, a project name, an output directory — that used to live scattered across dicts or global variables, where a mistyped key only failed at runtime. Turn them into a frozen data class and the settings live in one place, a mistyped key fails immediately, and changing a value takes a deliberate trip through the constructor instead of a casual assignment. The demo's Config is the minimal version of this pattern, with two fields; add more the same way.
Second, records and receipts: when you call a large model or an external API, turn the response into a data class before passing it along. For example, one call's record — model name, input tokens, output tokens, elapsed time — is four fields in one data class; cost calculations and statistics downstream are written against field names, never dict keys. AI-generated code is full of such records, and the temptation is to leave them as dicts "just to get it running", which ends with record["input_tokens"] all over the codebase; the day the API renames a field, the whole project fails at once. With data classes, the field names are pinned at construction, so a changed API fails in one place — at construction — where it is easy to find.
Third, replacing dict code that AI generated, one dict at a time: when you inherit AI-written code full of dicts being passed around, do not rewrite it all. Pick the most central dict — a task, an order, a user — replace it with a data class, run the tests, then move to the next one. One at a time, with tests after each step, keeps the risk of the refactor low. The pytest guide on this site covers writing those tests, and the data-class swap is a good place to use them as a guardrail: if all tests pass, the behavior is unchanged and only the structure is clearer. All three uses share one point: data classes are not for looking clever. They exist so that misspelled field names, wrong types, and invalid values surface at construction, instead of exploding somewhere in the middle of a run.
Closing checklist and boundaries
Here is the whole guide as a checklist to run the next time you reach for a data class in a vibe project: prefer data classes over dicts for anything that represents data; order fields with required ones first and defaulted ones after; use field(default_factory=...) for any list, dict, or set default; put validation in __post_init__ so every built instance is valid by default; add frozen=True to things that never change after construction, like configuration and coordinates; add order=True to things with a natural order, with field order as the sort order; save with asdict to dicts and then JSON, and load back by unpacking with ** and re-running validation; add slots=True when you want misspelled attribute names to fail loudly.
Finally, what this guide does not cover, so you do not take data classes where they do not belong: it does not cover validation libraries like Pydantic — data classes do not check types by default, and scenarios that need "fail when the type is wrong", such as validating data returned by an external API, belong to Pydantic, not to data classes; it does not cover third-party libraries like attrs, which look a lot like data classes and deserve their own comparison guide; and it does not teach object-oriented design systematically — inheritance, composition, abstract classes — the typing guide on this site already covers the annotation basics, while this guide only covers how to put data classes into a vibe project so they manage your data for you. On boundaries, one more reminder: this guide continues the Python basics series on the site — the file-I/O guide covers JSON saving and loading, the typing guide covers annotations, and this guide is what the two look like combined: structure, defaults, validation, and sorting, all from the standard library, with nothing else to install.
Comments (0)
Sources
Related articles
Five books in stock, 150930 cents in total, 35 copies; stock.json is 372 bytes, Promise.all reads 3 files into A+B+C, and the small service answers 200, 200, 404. Node v24.22.1 stdlib only, measured.
Adding a book parses to price=59.9, count=3, total 179.7; listing by price takes 2; four errors all exit with code 2; --pri abbreviates, and no subcommand parses to None. Python 3.12.3 stdlib, measured.
Building stock of 2000 books moves current memory from 0.3 KiB to 582.7 KiB; subtracting two snapshots, the biggest line is line 85 at 568.1 KiB and 9699 blocks; getsizeof sees only 15.8 KiB, and clearing brings the line back to 0.0 KiB. Python 3.12.3 stdlib, measured.