Python Dataclasses · Exercises
Object-Oriented Python

Python Dataclasses Exercises

4 exercises that build on the Python Dataclasses lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A dataclass is a normal class where you list the fields once, with type hints, and Python writes init, repr and eq for you, so classes that mostly hold data stay short and readable. By the end you can turn a data-holding class into a @dataclass, give fields defaults and default_factory, make instances immutable or sortable, validate and derive fields with post_init, convert objects with asdict(), astuple() and replace(), and decide when a plain class or a dict fits better. You will practise: Turn Book into a dataclass; Predict the playlists; Fix the leaderboard order; Build an invoice with line items.

0 / 4 completed

Python Dataclasses practice exercises

1. Turn Book into a dataclass

Write code Easy

Make Book a dataclass with the fields title (str), author (str) and pages (int, default 100). Do not write __init__ or __repr__ yourself.

For example Book("Dune", "Frank Herbert", 412) should print as Book(title='Dune', author='Frank Herbert', pages=412).

Your code
from dataclasses import dataclass

class Book:
    # add the decorator above the class and the three fields here
    pass

2. Predict the playlists

Predict the output Medium

Type exactly what the program prints. Think about which objects share a list and what replace() copies.

Read this code
from dataclasses import dataclass, field, replace

@dataclass
class Playlist:
    name: str
    songs: list = field(default_factory=list)
    plays: int = 0

focus = Playlist("Focus")
other = Playlist("Focus")
focus.songs.append("Rain")
focus.plays += 2
print(focus)
print(other)
print(focus == other)

gym = replace(focus, name="Gym")
gym.songs.append("Run")
print(gym.name, gym.plays, gym.songs)
print(focus.songs)

3. Fix the leaderboard order

Fix the bug Medium

leaderboard() should return the students with the highest score first, so the program should print 1 Ben 95, 2 Asha 82, 3 Chen 74. It lists them in a different order. order=True compares fields in the order they are declared. Fix the code so the leaderboard is sorted by score, highest first.

Your code
from dataclasses import dataclass

@dataclass(order=True)
class Student:
    name: str
    score: int

def leaderboard(students):
    return sorted(students, reverse=True)

students = [Student("Asha", 82), Student("Ben", 95), Student("Chen", 74)]
for place, student in enumerate(leaderboard(students), start=1):
    print(place, student.name, student.score)

4. Build an invoice with line items

Write code Hard

Write two dataclasses.

  1. LineItem with the fields name (str), unit_price (float), quantity (int, default 1) and a derived field total that is not an __init__ argument (init=False). In __post_init__, raise ValueError if quantity < 1 or unit_price < 0; otherwise set total to unit_price * quantity.
  2. Invoice with customer (str) and items, a list that is a new empty list for each invoice, plus a method grand_total() that returns the sum of the items' total values (0 for an empty invoice).

For example LineItem("Pen", 2.5, 4).total is 10.0.

Your code
from dataclasses import dataclass, field

# 1. LineItem: name, unit_price, quantity=1, total (init=False) + __post_init__

# 2. Invoice: customer, items (default_factory=list) + grand_total()

Next lessonWorking with JSON in Python

More Python Dataclasses examples · All Python exercises