0

First I define some types

from dataclasses import dataclass
from typing import Tuple,Union

@dataclass
class Point:
    x: float
    y: float



myPoint= Tuple[int,int]

otherPoint = Union[Tuple[int,int,int] , Tuple[int,int,str]]  

Shape = Union[Point , myPoint ,otherPoint]

AS you can see with print(Shape), Shape is an union type of 4 elements

typing.Union[main.Point, typing.Tuple[int, int], typing.Tuple[int, int, int], typing.Tuple[int, int, str]]

But the following code doesn't work.

def print_shape(shape: Shape):
    match shape:
        case Point(x, y):
            print(f"Point {x} {y}")
        case myPoint as mp:
            print(f"{mp[0]}{mp[1]}")
        case _ :
           print("point 3d")
print(Shape)
print_shape(Point(1, 2))
print_shape((5, 7))

case myPoint as mp: ^^^^^^^ SyntaxError: name capture 'myPoint' makes remaining patterns unreachable

There is 2 others pattern normaly after matching mypoint.

N.B. If you comment case _: , the works fine and as expected.

What is printed

Point 1 2

57

  • 2
    Does this answer your question? [Capture makes remaining patterns unreachable](https://stackoverflow.com/questions/67525257/capture-makes-remaining-patterns-unreachable) – slothrop Jun 21 '23 at 12:18
  • 1
    You claim it works fine if you remove the last case, but note myPoint case will match everything; `print_shape('hello')` which certainly isn't what you want. In case it's unclear, it's a confusing language feature with the match case and you need to follow the steps of putting your Point/otherPoint/myPoint names into e.g. a class namespace, like @siothrops link shows. – Mikael Öhman Jun 21 '23 at 12:41

0 Answers0