Odd name shadowing in comprehension
Steve D'Aprano
steve+python at pearwood.info
Sat Oct 22 23:44:21 EDT 2016
On Sun, 23 Oct 2016 11:51 am, eryk sun wrote:
> 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.
I don't think that this is relevant. Or rather, it might explain why the
behaviour is the way it is, but it isn't justification for it.
Here's a link to the PEP, showing the quote in context:
https://www.python.org/dev/peps/pep-0289/#early-binding-versus-late-binding
But this isn't a question about early or late binding, it is asking why the
variable y is treated as both global and local in the same comprehension.
This may be an unexpected side-effect of other choices, but I don't see any
discussion or consideration of this specific issue.
[Aside: Guido's quote in the PEP is unsourced; there's a reference given,
but it goes to a different email from Guido, not one that includes the
claimed explanation.]
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list