Lesson 5 of 10

Data classes

Goal

Write the fields, let Python write the rest

01

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.

02

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
  1. A new task has its default values
  2. Each task gets its own tag list
  3. The generated repr shows the fields
  4. Compares by value
  5. A Tag can't be changed after it's created
  6. A Tag works as a set member
main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.