Odd name shadowing in comprehension
eryk sun
eryksun at gmail.com
Sat Oct 22 20:51:50 EDT 2016
On Sat, Oct 22, 2016 at 11:57 PM, Chris Angelico <rosuav at gmail.com> wrote:
>
> Normally, a comprehension is described as being equivalent to an
> unrolled loop, inside a nested function.
> ...
> But it seems that the first iterator (and only that one) is evaluated
> in the parent context:
>
> Why is this? It seems rather curious.
It matches the behavior of generator expressions, for which Guido
gives the following example, as quoted in PEP 289:
Consider sum(x for x in foo()). Now suppose there's a bug in foo()
that raises an exception, and a bug in sum() that raises an
exception before it starts iterating over its argument. Which
exception would you expect to see? I'd be surprised if the one in
sum() was raised rather the one in foo(), since the call to foo()
is part of the argument to sum(), and I expect arguments to be
processed before the function is called.
More information about the Python-list
mailing list