[Python-ideas] Allow callable in slices
Nick Coghlan
ncoghlan at gmail.com
Sat Jun 9 11:06:42 EDT 2018
On 9 June 2018 at 19:20, Michel Desmoulin <desmoulinmichel at gmail.com> wrote:
> Given 2 callables checking when a condition arises and returning True:
>
> def starting_when(element):
> ...
>
> def ending_when(element:
> ...
> Allow:
>
> a_list[starting_when:]
>
> To be equivalent to:
>
> from itertools import dropwhile
>
> list(dropwhile(lambda x: not starting_when(x), a_list))
>
Custom container implementations can already do this if they're so
inclined, as slice objects don't type check their inputs:
>>> class MyContainer:
... def __getitem__(self, key):
... return key
...
>>> mc = MyContainer()
>>> mc[:bool]
slice(None, <class 'bool'>, None)
>>> mc[bool:]
slice(<class 'bool'>, None, None)
>>> mc[list:tuple:range]
slice(<class 'list'>, <class 'tuple'>, <class 'range'>)
It's only slice.indices() that needs start/stop/step to adhere to the
Optional[int] type hint.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180610/0f157981/attachment.html>
More information about the Python-ideas
mailing list