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 field
1from dataclasses import dataclass, field
# List is imported but not used in this example
2from typing import List
3
# @dataclass(frozen=True) makes the class immutable
4@dataclass(frozen=True)
# class Point is an immutable 2D point
5class Point:
# x coordinate as float
6 x: float
# y coordinate as float
7 y: float
8
# Method to calculate distance from origin
9 def distance_from_origin(self) -> float:
# Pythagorean theorem: sqrt(x^2 + y^2)
10 return (self.x ** 2 + self.y ** 2) ** 0.5
11
# Another frozen dataclass for polygons
12@dataclass(frozen=True)
# Polygon stores polygon data immutably (not used below)
13class Polygon:
# name identifies the polygon
14 name: str
# vertices stored as tuple for immutability
15 vertices: tuple = field(default_factory=tuple)
16
# Method to count vertices
17 def vertex_count(self) -> int:
# Return length of vertices tuple
18 return len(self.vertices)
19
# Create a Point at (3, 4)
20p1 = Point(3.0, 4.0)
# Create another Point with same coordinates
21p2 = 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 hashes
23print(f"Equal: {p1 == p2}, Hash: {hash(p1) == hash(p2)}")

Output

Distance: 5.0
Equal: True, Hash: True
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.

  • (× 14
  • )× 14
  • :× 11
  • =× 10
  • .× 9
  • _× 6
  • *× 6
  • ,× 4
  • "× 4
  • {× 3

More Python examples at level 5

← Python typing practice