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

Stephen J. Turnbull turnbull.stephen.fw at u.tsukuba.ac.jp
Sun Mar 4 06:10:47 EST 2018


Nick Coghlan writes:

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

This is horrible.  I think Julia is just weird: in normal English we
do distinguish between equality and membership.  "x in y" is a very
different statement from "x = y".  I think even Guido would come
around to the view if it were implemented (assuming not "over his dead
body").  But the semantics of "x = y" and "y as x" in English are both
pretty much the copula.  It's hard enough to stay aware that there be
dragons in a context manager; if "with" could denote a simple (local)
binding, it would require conscious effort.

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

This is *much* better.  But suppose you wanted to have *several*
bindings.  Would this syntax allow "destructuring" of tuples (as the
for clause will do):

    pairs = [(f(x) + g(y), f(x) - g(y)) for w, z in pairs_of_things
             with bind((h(w), k(z)) as (x, y)]

?  This is a question about all the proposals for local binding, I
think.

Steve



More information about the Python-ideas mailing list