Search code examples
pythonstructural-pattern-matching

How to structurally pattern match builtin type slice in python?


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.


Solution

  • 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