3

How to structurally pattern match builtin type slice in python?

Somewhy the following code does not work:

def __getitem__(self, index):
    match index:
        case int(i):
           ...
        case slice(start, stop, step):
           ...
        case _:
           ...

and I completely do not understand why.

PG_LoLo
  • 179
  • 10

2 Answers2

3

slice does not have a __match_args__ attribute, so it does not support positional patterns. It only supports keyword patterns for its three data descriptors start, stop and step.

match index:
    case int(i):
        print(f"Integer {i}")
    case slice(start=t1, stop=t2, step=t3):
        print(f"Start {t1} stop {t2} step {t3}")
    case _:
        print("Other")

(While PEP 634 seems to suggest that an AttributeError will be raised if you attempt to use positional patterns, it seems a TypeError is raised instead.)

chepner
  • 497,756
  • 71
  • 530
  • 681
2

Try:

class Example:
    def __getitem__(self, index):
        match index:
            case int(i):
                print('int', i)
            case slice(start=start, stop=stop, step=step):
                print('slice', start, stop, step)
            case _:
                print('default')

e = Example()
e[1]
e[1:2]

Prints:

int 1
slice 1 2 None
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91