[Python-ideas] A comprehension scope issue in PEP 572

Chris Angelico rosuav at gmail.com
Mon May 7 12:18:47 EDT 2018


On Tue, May 8, 2018 at 12:26 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> Here's a sketch of how I think locals are currently handled:
>
> 1. When a function is compiled, the compiler does a pass over the
>    source and determines which locals are needed.
>
> 2. The compiler builds an array of slots, one for each local,
>    and sets the initial value of the slot to "empty" (undefined).
>
> 3. When the function is called, if it tries reading from a local's
>    slot which is still empty, it raises UnboundLocalError.
>
> (am I close?)

Yeah, I'm pretty sure that's all correct.

> Here's the change I would suggest:
>
> 2. The compiler builds an array of slots, one for each local:
>
> 2a. For locals that are the target of binding-expression only:
>
>     - look up the target in the current scope (that is, not the
>       comprehension's scope, but the scope that the comprehension
>       is inside) using the normal lookup rules, as if you were
>       compiling "lambda x=x: None" and needed the value of x;
>
>     - if the target is undefined, then swallow the error and leave
>       the slot as empty;
>
>     - otherwise store a reference to that value in the slot.
>
> 2b. For all other locals, proceed as normal.

It's easy when you're not implementing things. I'm going to just say
"sure, go for it", and also not implement it. Have fun, whoever goes
in and tries to actually do the work...

I don't think there's any other construct in Python that can replicate
"a thing or the absence of a thing" in that way. For instance, there's
no way to copy a value from one dict into another, or delete from the
target dict if it isn't in the source (other than a long-hand). I've
no idea how it would be implemented, and don't feel like finding out.

ChrisA


More information about the Python-ideas mailing list