Usually slices are created with integers such as `foo[1:5]`. However slices are 
not restricted to having integers for the `start, stop, step` parameters and 
thus can be used with any types. The most prominent example is probably 
`pandas` which allows slicing by index (and the index can be `str` for example):

    df = pd.DataFrame([[0], [1], [2]], index=list('abc'), columns=['x'])
    print(df.loc['a':'b'])  # The first two items, 'a' and 'b' inclusive.

In one of my projects I also employed the slice syntax in a similar way. 
Sometimes more fine-grained control is desired, e.g. only allowing `str` slices 
and not `int` slices. For that purpose it would be constructive to explicitly 
indicate the type:

    class Foo:
        def __getitem__(self, index: Slice[str]):
            pass

    foo = Foo()
    foo[1:5]          # type checker complains
    foo['foo':'bar']  # no complaints here

The syntax would be somewhat similar to `slice` itself, with the difference 
that `Slice[T]` is similar to `Slice[T, T]`, i.e. specifying both the `start` 
and `stop` type.

Now with [PEP 
585](https://www.python.org/dev/peps/pep-0585/#importing-of-typing) using 
`slice` directly in annotations seems to be the preferred way, so I'm not even 
sure whether it is realistic to ask for such a new type being added to 
`typing`? Then, what else would it require for this idea to become part of the 
language (if accepted)?

Best regards,
Dominik
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/P4UVHUMVQHH26NXBYT6UGN6OOOOK7U4S/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to