Dataclass Frozen in Python

Level 4236 keystrokes

This creates an immutable dataclass with frozen=True. Frozen dataclasses cannot be modified after creation and can be used as dict keys.

Python code

# Import the dataclass decorator
1from dataclasses import dataclass
2
# frozen=True makes instances immutable: assigning p.x raises an error
3@dataclass(frozen=True)
4class Point:
# Fields are declared with type annotations
5 x: int
6 y: int
7
# A dataclass can still have regular methods
8 def distance_from_origin(self):
# Distance from the origin by the Pythagorean theorem
9 return (self.x ** 2 + self.y ** 2) ** 0.5
10
# The generated __init__ sets x=3 and y=4
11p = Point(3, 4)
# {p} uses the generated __repr__; the distance is 5.0
12print(f"Point: {p}, Distance: {p.distance_from_origin()}")

Output

Point: Point(x=3, y=4), Distance: 5.0
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.

  • :× 6
  • (× 6
  • )× 6
  • *× 6
  • _× 4
  • .× 4
  • ,× 2
  • "× 2
  • {× 2
  • }× 2

More Python examples at level 4

← Python typing practice