[Python-ideas] An alternative to PEP 572's Statement-Local Name Bindings

Nick Coghlan ncoghlan at gmail.com
Sat Mar 3 02:40:03 EST 2018


On 3 March 2018 at 11:36, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:

> PEP 572 as it stands seems to have many problems:
>
> * Asymmetry between the first and subsequent
>   uses of the bound value
> * Embedded as-clauses are subtle and hard to spot
> * Ever more convoluted semantics are being invented
>   to address percieved pitfalls
>
> Alternative proposal
> --------------------
>
> Getting back to the original motivating use case of
> intermediate values in comprehensions, to my mind there
> is really only one clear and obvious way to write such
> things:
>
>    [(f(y), g(y)) for x in things where y = h(x)]
>


I know Guido is on record as not wanting to allow both "for name in
sequence" and "for name = expr" due to that being a very subtle distinction
between iteration and simple assignment (especially given that Julia uses
them as alternate spellings for the same thing), but I'm wondering if it
may be worth considering such a distinction in *with statements*, such that
we allowed "with name = expr" in addition to "with cm as name" (where "name
= expr" is just an ordinary assignment statement that doesn't trigger the
context management protocol).

The related enhancement to comprehensions would then be to allow with
clauses to be interleaved between the for loops and the if statements, such
that you could write things like:

    pairs = [(f(y), g(y)) for x in things with y = h(x)]
    contents = [f.read() for fname in filenames with open(fname) as f]

while still preserving the property where comprehensions can be correctly
interpreted just by converting each of the clauses to the corresponding
statement form.

Even without the "with name = expr" change, allowing with clauses in
comprehensions would let you do (by way of a suitably defined "bind" CM):

    pairs = [(f(y), g(y)) for x in things with bind(h(x)) as y]

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/20180303/00377db0/attachment.html>


More information about the Python-ideas mailing list