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 field
1from dataclasses import dataclass, field
2
# @dataclass generates __init__ and __repr__ from the fields
3@dataclass
4class Person:
# No default: name must be passed
5 name: str
# A simple default of 0
6 age: int = 0
# Mutable default: default_factory creates a new list per instance
7 tags: list = field(default_factory=list)
8
# Pass only name; age and tags use their defaults
9p = Person("Alice")
# The generated __repr__: Person(name='Alice', age=0, tags=[])
10print(p)

Output

Person(name='Alice', age=0, tags=[])
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.

  • :× 4
  • =× 4
  • (× 3
  • )× 3
  • "× 2
  • _× 1
  • ,× 1
  • @× 1

More Python examples at level 4

← Python typing practice