Dataclass with Defaults in Python
Level 4160 keystrokes
This creates a dataclass with default values and a mutable default using field().
Python code
# field lets you configure a single dataclass field1from dataclasses import dataclass, field2 # @dataclass generates __init__ and __repr__ from the fields3@dataclass4class Person: # No default: name must be passed5 name: str # A simple default of 06 age: int = 0 # Mutable default: default_factory creates a new list per instance7 tags: list = field(default_factory=list)8 # Pass only name; age and tags use their defaults9p = Person("Alice")# The generated __repr__: Person(name='Alice', age=0, tags=[])10print(p)Output
Person(name='Alice', age=0, tags=[])
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.
:× 4=× 4(× 3)× 3"× 2_× 1,× 1@× 1