How to structurally pattern match builtin type slice in python?

126 Views Asked by At

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.

2

There are 2 best solutions below

1
Andrej Kesely On BEST ANSWER

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
0
chepner On

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.)