Dataclass Field Factory in Python

Level 5405 keystrokes

This shows advanced dataclass features: field() with default_factory, repr control, and __post_init__ hook.

Python code

# Import dataclass decorator and field function
# field() customizes individual dataclass attributes
1from dataclasses import dataclass, field
# Import List from typing for type hints
2from typing import List
3
# @dataclass auto-generates __init__, __repr__, etc.
4@dataclass
# Team class represents a team with members
5class Team:
# name is a required field (no default)
6 name: str
# members uses default_factory to create new list for each instance
# Avoids mutable default argument bug
7 members: List[str] = field(default_factory=list)
# score has default 0, repr=False hides it from __repr__
8 score: int = field(default=0, repr=False)
9
# add_member is a regular method
# Appends member to the members list
10 def add_member(self, member: str) -> None:
11 self.members.append(member)
12
# __post_init__ runs after __init__ completes
# Useful for validation or logging
13 def __post_init__(self):
# Print message when team is created
14 print(f"Team {self.name} created!")
15
# Create Team with name "Alpha"
# __post_init__ prints "Team Alpha created!"
16team = Team("Alpha")
# Add Alice to the team
17team.add_member("Alice")
# Add Bob to the team
18team.add_member("Bob")
# Print team (score hidden because repr=False)
19print(team)

Output

Team Alpha created!
Team(name='Alpha', members=['Alice', 'Bob'])
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 10
  • )× 10
  • _× 9
  • "× 8
  • :× 7
  • =× 6
  • .× 5
  • ,× 3
  • -× 1
  • !× 1

More Python examples at level 5

← Python typing practice