When indexing a list, it’s useful to get a subset of the elements of the list, and that’s what slices are for. But while the indices requested by the slice object follow useful rules matching the most common uses, it could sometimes be useful to program alternative rules for the generation of these indices.
A typical use would be the emulation of passing lists or other arrays as indices to numpy array. When you do arr[[1, 5, 4, 18]]
(notice the double square brackets), you’re requesting another array made of the first, fifth, fourth and eighteenth element of the initial array. This irregular sequence of indices would not be doable using a slice.
Enabling this opens another door : slice-like behavior for mappings. If my slice-like object returns a sequence of keys, I get in return a dict made of these keys and of their values in the original dict.
You’re probably thinking “that could and should be done in a user-defined function, or using comprehension syntax such as [arr[k] for k in [1, 5, 4, 18]]
”.
That’s true, but it only works for the __getitem__
side of slicing, not for the __setitem__
side ! I would like to be able to do this as well indexable[myslicelike] = some_sequence
. With lists, but also with dicts.
I’m proposing to create a new __slice__
method in the datamodel, which would return a sequence or iterable. When indexing a list or a dict (or a tuple, in a getitem situation), if the given index object is not a valid integer (for sequences) or key (for dicts), the __slice__
method is called on the index to obtain a sequence of indices. And then, the usual setitem, getitem or delitem behavior takes place.
The arguments to pass to the method are debatable : the vanilla slice needs to know the size of the sequence, but other information could be useful (for dicts, that would be the set of keys typically). And at the same time, passing the object itself could allow the method to mutate it, which is not ideal. We could always state it’s not meant to be done, like mutating a list that’s being sorted… I have no definitive view on that question, so please target other aspects of the idea for initial critics