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

Robert Vanden Eynde robertve92 at gmail.com
Sun Mar 4 13:18:00 EST 2018


> 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]

Including standard "with open(...) as f" context management in list
comprehensions would also be a good idea, I think it's in the same
idea as including : allowing both statements (imperative programming)
and list comprehension (more "functional"). The same story goes for
exceptions :

    for x in range(5):
       try:
           yield f(x)
       except Exception:
           yield 0

isn't "refactorable" as a list comprehension like :

    [try f(i) except Exception: 0 for x in range(5)]

But I think that would cover another subject :)

But if the "with =" syntax is accepted for simple assignment, it could
indeed introduce a confusion compared to the "with as" in context
management, and having a complete different keyword (or punctuation)
is maybe be better.

As a symmetry, we could also introduce the "with =" syntax in normal
statement :P that'd do a normal assignement, although that's be
probably stupid because normal assignements works well.

Robert


More information about the Python-ideas mailing list