Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python Dataclasses Code

Practice generated class methods, per-instance mutable defaults, post-initialization, and frozen data records.

Intermediate ~9 min read

Challenge 1

Add the decorator that generates an initializer, representation, and equality for this record.

python Your answer
from dataclasses import dataclass


class Meal:
    name: str
    portions: int = 1

meal = Meal("soup")
print(meal)
print(meal.portions)

Press Ctrl⌘Enter to check your answer

Challenge 2

Use a factory so each Basket receives its own list of items.

python Your answer
from dataclasses import dataclass, field

@dataclass
class Basket:
    items: list[str] = 

first = Basket()
second = Basket()
first.items.append("pear")
print(first.items)
print(second.items)

Press Ctrl⌘Enter to check your answer

Challenge 3

Complete __post_init__ so area is calculated from width and height after initialization.

python Your answer
from dataclasses import dataclass, field

@dataclass
class Rectangle:
    width: int
    height: int
    area: int = field(init=False)


rectangle = Rectangle(4, 5)
print(rectangle.area)

Press Ctrl⌘Enter to check your answer

Challenge 4

Use a frozen dataclass so normal assignment to the coordinate fields is blocked.

python Your answer
from dataclasses import dataclass, FrozenInstanceError


class Coordinate:
    x: int
    y: int

point = Coordinate(2, 5)
try:
    point.x = 8
except FrozenInstanceError:
    print("field assignment blocked")

Press Ctrl⌘Enter to check your answer