[Python-ideas] Integrate some itertools into the Python syntax

Paul Moore p.f.moore at gmail.com
Wed Mar 23 09:43:11 EDT 2016


On 23 March 2016 at 13:01, Franklin? Lee <leewangzhong+python at gmail.com> wrote:
> I like this. I don't think it should happen, due to existing parts of the
> language it might step on, but I like it.
>
> foo(f:g:h) will mean
>
>     filter(h, takewhile(g, dropwhile(negate(f), foo)))
>
> (possibly clearer if we imagine being able to write:
>      Itertooler(foo).dropwhile(negate(f)).takewhile(g).filter(h)
> )
>
> where
>
>     def negate(f):
>         def negate_f(*args, **kwargs):
>             return not f(*args, **kwargs)
>         return negate_f

As an alternative, you could use a "pipeline" style of approach, as
shown in Steven D'Aprano's recipe at
http://code.activestate.com/recipes/580625-collection-pipeline-in-python/

foo | SkipUntil(f) | While(g) | Filter(h)

(the recipe doesn't define SkipUntil or While, but it's not hard to
see how you would write them). As a side note, your code does
takewhile(g), where I think the original proposal would have done
takeuntil(g) (takewhile(negate(g)) - which is another argument for
having explicit named filtering operations rather than implicit
behaviour based on syntax.

Honestly, something like this looks much more readable to me than
playing games with the slice syntax.

Paul


More information about the Python-ideas mailing list