Dataclass Frozen in Python
Level 5508 keystrokes
This creates immutable dataclasses with frozen=True that can be hashed and used as dict keys.
Python code
# Import dataclass and field1from dataclasses import dataclass, field# List is imported but not used in this example2from typing import List3 # @dataclass(frozen=True) makes the class immutable4@dataclass(frozen=True)# class Point is an immutable 2D point5class Point: # x coordinate as float6 x: float # y coordinate as float7 y: float8 # Method to calculate distance from origin9 def distance_from_origin(self) -> float: # Pythagorean theorem: sqrt(x^2 + y^2)10 return (self.x ** 2 + self.y ** 2) ** 0.511 # Another frozen dataclass for polygons12@dataclass(frozen=True)# Polygon stores polygon data immutably (not used below)13class Polygon: # name identifies the polygon14 name: str # vertices stored as tuple for immutability15 vertices: tuple = field(default_factory=tuple)16 # Method to count vertices17 def vertex_count(self) -> int: # Return length of vertices tuple18 return len(self.vertices)19 # Create a Point at (3, 4)20p1 = Point(3.0, 4.0)# Create another Point with same coordinates21p2 = Point(3.0, 4.0)# Prints 5.0 (3-4-5 right triangle)22print(f"Distance: {p1.distance_from_origin()}")# Same field values: equal, and frozen makes them hashable with equal hashes23print(f"Equal: {p1 == p2}, Hash: {hash(p1) == hash(p2)}")Output
Distance: 5.0 Equal: True, Hash: True
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.
(× 14)× 14:× 11=× 10.× 9_× 6*× 6,× 4"× 4{× 3