[Python-ideas] PEP 572 version 2: Statement-Local Name Bindings

Nick Coghlan ncoghlan at gmail.com
Sun Mar 25 09:43:06 EDT 2018


On 25 March 2018 at 22:44, Christoph Groth <christoph at grothesque.org> wrote:
> I think that it's a helpful guideline to imagine what the ideal behavior
> should be if we were not constrained by backwards compatibility, and
> then try to follow it.  In the case at hand, we all seem to agree that
> the fact that the outermost iterator of a comprehension is evaluated in
> the surrounding scope is somewhat of a wart, although one that is rarely
> visible.

There's no such agreement, since generator expressions have worked
that way since they were first introduced almost 15 years ago:
https://www.python.org/dev/peps/pep-0289/#the-details

It's much easier to see the difference with generator expressions,
since the evaluation of the loop body is delayed until the generator
is iterated over, while the evaluation of the outermost iterator is
immediate (so that any exceptions are more easily traced to the code
responsible for them, and so that they don't need to create a closure
in the typical case).

With comprehensions, the entire nested scope gets evaluated eagerly,
so it's harder to detect that there's a difference in the evaluation
scope of the outermost iterator in normal use. That difference *does*
exist though, and we're not going to tie ourselves into knots to try
to hide it (since the exact same discrepancy will necessarily exist
for generator expressions, and semantic consistency between genexps
and the corresponding comprehensions is highly desirable).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list