[Python-ideas] Reuse "for" to express "given"

Alexander Belopolsky alexander.belopolsky at gmail.com
Thu May 24 11:54:09 EDT 2018


I have read most of the PEP 572 related threads, but I don't think I've
seen this idea.  As many other people mentioned, Python already allows a
trick to introduce local bindings in generator expressions and list
comprehensions.  This can be achieved by adding a "for var in [<expr>]"
clause.  I propose to make "for var = <expr>" have the same effect as "for
var in [<expr>]".

Note that in the case of filters, the order will be different from that in
the original "given" proposal: instead of

[(x, y, x/y) for x in data if y given y = f(x)]

we will write

[(x, y, x/y) for x in data for y = f(x) if y]

The use of "for" in place of "given" in the if statements does not look too
bad:

   if m for m = pattern.search(data):
        ...
    elif m for m = other_pattern.search(data)):
        ...
    else:
        ...

I have to admit that

while m for m = pattern.search(remaining_data):
        ...

looks strange at first because both while and for are strongly associated
with loops, but if you read "for var = <expr>" as "for var equals
expression", the difference between that and "for var in (iterable)
expression" becomes apparent.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180524/7f549e06/attachment.html>


More information about the Python-ideas mailing list