Last active
June 1, 2023 05:05
-
-
Save mtavkhelidze/066e8879339804dc0696df76beac67e3 to your computer and use it in GitHub Desktop.
Scala-like case class pattern matching in Python >= 3.10
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
from dataclasses import dataclass | |
from math import sqrt | |
""" | |
Scala-like case class pattern mathing in python >= 3.10 | |
""" | |
@dataclass(frozen=True) | |
class Shape: | |
"""trait""" | |
pass | |
@dataclass(frozen=True) | |
class Circle(Shape): | |
"""case class""" | |
radius: int | |
@dataclass(frozen=True) | |
class Square(Shape): | |
"""case class""" | |
side: int | |
@dataclass(frozen=True) | |
class Triangle(Shape): | |
"""case class""" | |
a: int | |
b: int | |
c: int | |
def heron(a: int, b: int, c: int) -> float: | |
s: float = (a + b + c) / 2 | |
return sqrt(s * (s - a) * (s - b) * (s - c)) | |
def shape_area(s: Shape) -> float: | |
match s: | |
case Circle(radius): | |
return math.pi * (radius ** 2) | |
case Square(side): | |
return side ** 2 | |
case Triangle(a, b, c): | |
return heron(a, b, c) | |
case _: | |
raise f"Cannot handle shape {s.__class__.__name__}" | |
c = Circle(12) | |
s = Square(13) | |
t = Triangle(3, 4, 5) | |
print(f"Circle({c.radius}): {shape_area(c):.2f}") | |
print(f"Square({s.side}): {shape_area(s)}:2f") | |
print(f"Triangle({t.a, t.b, t.c}): {shape_area(t):.2f}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment