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 decorator1from dataclasses import dataclass2 # frozen=True makes instances immutable: assigning p.x raises an error3@dataclass(frozen=True)4class Point: # Fields are declared with type annotations5 x: int6 y: int7 # A dataclass can still have regular methods8 def distance_from_origin(self): # Distance from the origin by the Pythagorean theorem9 return (self.x ** 2 + self.y ** 2) ** 0.510 # The generated __init__ sets x=3 and y=411p = Point(3, 4)# {p} uses the generated __repr__; the distance is 5.012print(f"Point: {p}, Distance: {p.distance_from_origin()}")Output
Point: Point(x=3, y=4), Distance: 5.0
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