Lesson 5 of 10
Data classes
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
Write the fields, let Python write the rest
Explanation
Most classes just hold data. __init__ copies the parameters onto self, then __repr__ and __eq__ repeat the same fields. Add a field, forget to update __eq__, and you have a bug nothing warns you about.
@dataclass writes these methods for you from the fields you declare with their types. Write done: bool = False and it becomes a parameter with a default value, and you get a repr that shows the fields, plus comparison by value, without writing a single extra line. frozen=True stops the object from being changed after it's created, and makes it usable in sets and as a dict key.
It also protects you from an old trap with mutable default values. The list in tags=[] inside __init__ is created once, when the function is defined, so every object shares it. That's why @dataclass refuses it. The alternative is field(default_factory=list), which makes a new list for each object.
Your task
Turn Task into a dataclass with the fields title, done (defaulting to False) and tags (a new list for every task), and turn Tag into a frozen dataclass that can't be changed, with the fields name and color (defaulting to "gray").
Checks
6 checks- A new task has its default values
- Each task gets its own tag list
- The generated repr shows the fields
- Compares by value
- A Tag can't be changed after it's created
- A Tag works as a set member