Dataclasses & Enums
You'll learn to
- -Use `@dataclass` to eliminate boilerplate `__init__`, `__repr__`, and `__eq__` code
- -Define a set of named constants with `Enum`
- -Explain what each feature saves you from writing by hand
The OOP module showed you how to write `__init__`, `__repr__`, and `__eq__` by hand for a class that is mostly just a bundle of data - and how easy it is to forget one, or let them drift out of sync as the class grows. `dataclasses` and `Enum` are two standard-library tools that eliminate exactly that kind of repetitive, error-prone boilerplate.
@dataclass: Boilerplate, Automated
Recall the `Point` class from the dunder methods chapter, where `__init__`, `__str__`/`__repr__`, and `__eq__` all had to be written out by hand. `@dataclass` generates all of that automatically from a list of annotated fields.
A single `@dataclass`-decorated class with type-annotated fields gets a generated `__init__` (one parameter per field), `__repr__` (a clean, readable one, same shape you'd write by hand), and `__eq__` (field-by-field comparison) - all three of the dunder methods from the OOP module, for free, kept perfectly in sync as you add or rename fields.
Enum: Named Constants Done Right
Before `Enum`, a common way to represent "one of a fixed set of options" was plain strings or integers - `status = "pending"` - which is easy to typo (`"pednign"`) with no error until something breaks downstream. `Enum` gives each option a real name that is checked at the point of use.
A typo like `Status.PENDIGN` fails immediately with an `AttributeError` at the point of the mistake, rather than silently comparing two mismatched strings somewhere much later. `Enum` members are also naturally self-documenting - `Status.COMPLETE` reads clearly at every call site, compared to a bare `"complete"` string with no indication of what the full set of valid options even is.
Same caveat as the previous chapter: the Forge Algorithm Lab's sandbox import allowlist does not include `dataclasses`, so `@dataclass` specifically isn't available inside lab submissions - but `enum` is on the allowlist, so `Enum` works fine there. Both are genuinely standard, widely used tools in real Python codebases outside the lab, which is why they are worth learning properly here.
- -`@dataclass` generates `__init__`, `__repr__`, and `__eq__` from annotated fields - the exact trio you wrote by hand in the OOP module's dunder methods chapter.
- -`Enum` replaces "magic" strings/numbers for a fixed set of options with named, typo-proof, self-documenting members.
- -Inside the Forge Algorithm Lab sandbox: `enum` is importable, `dataclasses` is not - plain classes with hand-written `__init__` still work everywhere.