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([, , ], 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:
def __getitem__(self, index: Slice[str]):
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)?
Python-ideas mailing list -- firstname.lastname@example.org
To unsubscribe send an email to email@example.com
Message archived at https://firstname.lastname@example.org/message/P4UVHUMVQHH26NXBYT6UGN6OOOOK7U4S/
Code of Conduct: http://python.org/psf/codeofconduct/