Legends ofPythos
Claim your name
Objects and Classes

Less boilerplate with dataclasses

Lesson 12 of 13

Watch the lesson5:28 · with Torsten
You have been writing __init__ methods by hand. You list the parameters, then you assign each one to self. For a class with ten attributes, that is ten lines of self.x = x just to copy data around.

Python has a tool for exactly this: dataclasses.

The @dataclass decorator

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int
A class with two fields and no methods.
The @dataclass decorator looks at the lines inside your class. Each line like x: int is a field: a name, a colon, then a type. int means a whole number. Python doesn't check the type, but without the colon and the type, the line isn't a field. The decorator automatically writes an __init__ method that accepts one argument per field.

You can now create objects by passing one value per field.
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p = Point(3, 7)
print(p.x)   # 3
print(p.y)   # 7

Free repr and equality

Dataclasses also generate __repr__ for you. Printing an object shows its type name and field values in a readable format.

It generates __eq__ too, so two dataclass instances are equal if their fields match.
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

a = Point(3, 7)
b = Point(3, 7)
c = Point(1, 2)

print(a)          # Point(x=3, y=7)
print(a == b)     # True
print(a == c)     # False

Field defaults

You can give a field a default value. Any parameter with a default becomes optional when you create the object.

One rule: fields without defaults must come before fields that have them.

In the example below, str means text, and bool means True or False.
from dataclasses import dataclass

@dataclass
class User:
    name: str
    age: int = 0
    admin: bool = False

Your turn

0 of 2 solved

Exercise 1

+40 XP
Define a dataclass called Book with two fields: title (text, so str) and pages (a whole number, so int, defaulting to 0). Then create an instance named my_book using the title 'Dune' and pages 412. Finally, print the object.
Write your Python here.

Run your code to check it against the tests.

Exercise 2

+40 XP
Define a dataclass called Task with fields: name (str) and done (bool, default False). Create two tasks, both named 'write tests', and assign them to t1 and t2. Then print whether they are equal (True or False). Print nothing else.
Write your Python here.

Run your code to check it against the tests.