liveBook · Manning

Default_factory

As explained in Python Workout: 50 ten-minute exercises

default_factory is a dataclass field configuration that supplies a callable for creating a fresh default value for each instance.

A mutable list should not be assigned as one shared default. Configure the dataclass field with default_factory=list so each new Bowl invokes list and receives a fresh scoops list. section 9.10

Fresh scoop lists with a dataclass

from typing import List from dataclasses import dataclass, field @dataclass class Bowl(): scoops: List[Scoop] = field(default_factory=list) def add_scoops(self, *new_scoops): for one_scoop in new_scoops: self.scoops.append(one_scoop) def __repr__(self): return '\n'.join(s.flavor for s in self.scoops)

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains why a callable creates a new list, without descending into dataclass internals.
Examples
Uses a Bowl dataclass whose scoops field calls list for each new default.
What it assumes
Assumes familiarity with Python classes, dataclasses, type annotations, and mutable lists.
What you can do after
Build it from scratch by configuring a dataclass list field with field(default_factory=list).
How it connects
Connects dataclasses, field configuration, mutable lists, and type annotations.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.