Safe List Default with field()
Beginner · Fix the bug · from Advanced Dataclasses: __post_init__, frozen, field(), slots, and Inheritance
From the lesson: Advanced Dataclasses: __post_init__, frozen, field(), slots, and Inheritance
You already know the basics of dataclasses - how to define fields, get automatic __init__ and __repr__, and set default values. Now it's time to unlock the advanced features.
Read the lessonThis code tries to give each Playlist its own list of songs, but it will crash because mutable defaults are not allowed. Fix it using field(default_factory=list).
from dataclasses import dataclass
@dataclass
class Playlist:
name: str
songs: list = []
p1 = Playlist('Rock')
p1.songs.append('Thunder')
p2 = Playlist('Pop')
p2.songs.append('Flowers')
print(f'{p1.name}: {p1.songs}')
print(f'{p2.name}: {p2.songs}')
More Advanced Dataclass exercises
- Validate with __post_init__Beginner
- Predict the Output: Frozen DataclassIntermediate
- Computed Field with __post_init__Intermediate
- Dataclass InheritanceAdvanced
- Refactor: Add Validation and Computed FieldsAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz