Created
December 9, 2022 15:29
-
-
Save krummja/4c8a75b4be88ed478389cc5ef49d49d5 to your computer and use it in GitHub Desktop.
Python 3.10+ Structural Pattern Matching
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
from __future__ import annotations | |
from typing import NamedTuple | |
class Point2D(NamedTuple): | |
x: int | |
y: int | |
class Point3D(NamedTuple): | |
x: int | |
y: int | |
z: int | |
def make_point_3d_old(point: tuple[int, ...] | Point2D) -> Point3D: | |
if isinstance(point, Point2D): | |
return Point3D(point.x, point.y, 0) | |
elif isinstance(point, Point3D): | |
return point | |
elif isinstance(point, tuple): | |
if len(point) == 2: | |
return Point3D(point[0], point[1], 0) | |
elif len(point) == 3: | |
return Point3D(point[0], point[1], point[2]) | |
else: | |
raise TypeError("Requires tuple length l: 1 < l <= 3") | |
else: | |
raise TypeError("Not a supported point type") | |
def make_point_3d(point: tuple[int, ...] | Point2D) -> Point3D: | |
match point: | |
case (x, y): | |
return Point3D(x, y, 0) | |
case (x, y, z): | |
return Point3D(x, y, z) | |
case Point2D(x, y): | |
return Point3D(x, y, 0) | |
case Point3D(_, _, _): | |
return point | |
case _: | |
raise TypeError("Not a supported point type") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment