Editor

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 lesson

This 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

All Python exercises · 50 practice problems · Object-Oriented Programming quiz