[Python-ideas] Map-then-filter in comprehensions

Pavol Lisy pavol.lisy at gmail.com
Thu Mar 10 11:53:36 EST 2016


2016-03-09 6:16 GMT+01:00, Sjoerd Job Postmus <sjoerdjob at sjec.nl>:
[...]
> Trying to word it in such a way:
>
> "... considering each of the `for` or `if` clauses a block, nesting from
> left to right, and evaluating the expression to produce an element each
> time the innermost block is reached. The `with expr as target` should be
> considered equivalent to `target = expr`.
>
> (And here we already see the downside of this idea). Normally a
> comprehension of the form
>
>     (expr1 for target1 in expr2 for target2 in expr3 if expr4)
>
> boils down to
>
>     for target1 in expr2:
>         for target2 in expr3:
>             if expr4:
>                 yield expr1
>
> The natural extension would be for
>
>     (expr1 for target1 in expr2 with expr3 as target2 if expr4)
>
> to reduce as follows.
>
>     for target1 in expr2:
>         with expr3 as target2:
>             if expr4:
>                 yield expr1
>
> Instead, it becomes
>
>     for target1 in expr2:
>         target2 = expr3:
>         if expr4:
>             yield expr1
>
> But of course we're not going to have context managers in
> comprehensions, are we? So this inconsistency is somewhat forgiveable.

If we want variable assignment we have already "for var in [expr]" syntax.

We could discuss if "with expr as var" syntax is more beautiful. (or
if it not against There should be one-- and preferably only one
--obvious way to do it.)

But why omit context manager semantics in "with expr as var" assignment syntax?

I personally don't like idea that semantics could be context sensitive
in this way. (and we could already do pretty complex things in
comprehension)


More information about the Python-ideas mailing list