Legends ofPythos
Claim your name
Objects and Classes

Less boilerplate with dataclasses

Lesson 12 of 13

Watch the lesson1:13 · 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. 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.
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 (a string) and pages (an 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), done (bool, default False). Create two instances: one for 'write tests' and one also named 'write tests'. Assign them to variables t1 and t2. Then print whether they are equal.
Write your Python here.

Run your code to check it against the tests.