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 attributes1from dataclasses import dataclass, field# Import List from typing for type hints2from typing import List3 # @dataclass auto-generates __init__, __repr__, etc.4@dataclass# Team class represents a team with members5class 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 bug7 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 list10 def add_member(self, member: str) -> None:11 self.members.append(member)12 # __post_init__ runs after __init__ completes # Useful for validation or logging13 def __post_init__(self): # Print message when team is created14 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 team17team.add_member("Alice")# Add Bob to the team18team.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. 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