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

Tim Peters tim.peters at gmail.com
Sun May 13 20:00:59 EDT 2018


[Tim]
>> - If the target is not local to any function enclosing F, and is not
>> declared `global` in the block containing F, then the target is bound
>> in the block containing F.

[also Tim]
> FYI, that's still not right, ...
> I suspect that the above should be reworded to the simpler:
>
> - If the target is not  declared `global` or `nonlocal` in the block
>   containing F, then the target is bound in the block containing F.
> ...

I'm satisfied that captures the intent - but now it's misleadingly
wordy.  It should be the briefer:

- The target is bound in the block containing F.

Other text (in section 4.2.2) already covers the intended meanings for
when a `global` or `nonlocal` declaration appears in the block too.

And then it's short enough again that the bullet list isn't really
helpful anymore.  So, putting that all together:

"""
An assignment expression binds the target, except in a function F
synthesized to implement a list comprehension or generator expression
(see XXX).  In the latter case[1], the target is bound in the block
containing F, and errors may be detected:  If the target also appears
as an identifier target of a `for` loop header in F, a `SyntaxError`
exception is raised.  If the block containing F is a class block, a
`SyntaxError` exception is raised.

Footnote:
[1] The intent is that runtime binding of the target occurs as if the
binding were performed in the block containing F.  Because that
necessarily makes the target not local in F, it's an error if the
target also appears in a `for` loop header, which is a local binding
for the same target.  If the containing block is a class block, F has
no access to that block's scope, so it doesn't make sense to consider
the containing block.  The target is bound in the containing block,
where it inherits that block's `global` or `nonlocal` declaration if
one exists, else establishes that the target is local to that block.
"""

Along with the previous:

>     ... targets that are identifiers if occurring in an assignment, ...
>
> " statement" should be inserted before the comma.


Of course there are other docs that need to change too.  I viewed this
as the hardest part (witness how long it took to reduce it to
near-triviality ;-) ), so wanted to get it out of the way first.


More information about the Python-ideas mailing list