field()
- Python course
- Intermediate
- Lesson 54/116
- 5 min
Learn defaults with field(default_factory=...).
What is field() for?
When a field's default is a mutable object (list, dict, set), you cannot write = [] directly; Python would share it across all instances. Instead, use field(default_factory=list); each new instance gets its own empty list.
Example: members: list = field(default_factory=list). This line calls list() for each new instance and gives a separate empty list. You can pass dict, set or your own function to default_factory.
The shared-list trap
If you write members: list = [], Python uses the same list for all instances. This is a subtle bug: an item added in one instance also appears in another. field(default_factory=list) removes this trap completely.
Similarly, use field(default_factory=dict) for a dict, field(default_factory=set) for a set. For immutable types (int, str, tuple) you can write the default directly; no issue arises.
Practice Add a field to the Team class
Start with from dataclasses import dataclass, field. Define a Team class with @dataclass; include fields name: str = "" and members: list = field(default_factory=list). Add a method def add(self, m): with body self.members.append(m). Then create t = Team(name="Stars"), add a member with t.add("Ayşe") and print with print(len(t.members)).
Starter code
# Write the Team dataclass with fieldSample solution
# Write the Team dataclass with field
from dataclasses import dataclass, field
@dataclass
class Team:
name: str = ""
members: list = field(default_factory=list)
def add(self, m):
self.members.append(m)
t = Team(name="Stars")
t.add("Ayşe")
print(len(t.members))Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the default_factory call
from dataclasses import dataclass, field
@dataclass
class Team:
name: str = ""
members: list = field(default_factory=____)
def add(self, m):
self.members.append(m)
from dataclasses import dataclass, field
@dataclass
class Team:
name: str = ""
members: list = field(default_factory=list)
def add(self, m):
self.members.append(m)
Explanation: default_factory=list gives each instance its own empty list.
2 What does members: list = [] cause?
- A syntax error
- Nothing, no problem
- Auto-generates an empty list
- All instances share the same list Correct answer
Explanation: Direct [] shares the same list across all instances; this is a bug.
3 Match the field() parts
| Term | Meaning |
|---|---|
field |
Function |
default_factory |
Factory argument |
list |
Builds empty list |
dict |
Builds empty dict |