[Python-Dev] Checking that PEP 558 (defined semantics for locals()) handles assignment expressions

Guido van Rossum guido at python.org
Thu Jul 5 18:57:36 EDT 2018

On Thu, Jul 5, 2018 at 3:06 PM Nick Coghlan <ncoghlan at gmail.com> wrote:

> On Thu., 5 Jul. 2018, 1:21 am Guido van Rossum, <guido at python.org> wrote:
>> Correct, there shouldn't be any additional corner cases for your PEP due
>> to inline assignments. We're not introducing new scopes nor other runtime
>> mechanisms; the target of an inline assignment is either a global or a cell
>> (nonlocal) defined at a specific outer level.
> Cool. I'll still review the PEP to see if it makes sense to mention this
> as a side note anywhere, but it may turn out to make more sense to simply
> not mention it at all.

Would it be helpful if PEP 572 spelled out the translations of some common
and corner cases? It's difficult to present a general rule for translating
because of the required static analysis (not impossible but it would be low
information density compared to the spec that's already there), but it
might help clarify the spec for implementers who aren't from Mars.

> What I wish we had (quite independent from PEP 572) is a way in a debugger
>> to evaluate a comprehension that references a local in the current stack
>> frame. E.g. here's something I had in a pdb session yesterday:
>> (Pdb) p [getattr(context.context, x) for x in dir(context.context)]
>> *** NameError: name 'context' is not defined
>> (Pdb) global cc; cc = context
>> (Pdb) p [getattr(cc.context, x) for x in dir(cc.context)]
>> [<class 'mypy.nodes.CallExpr'>, ............]
>> (Pdb)
>> The first attempt failed because the outer `context` was a local variable
>> in some function, and pdb uses eval() to evaluate expressions.
> Perhaps pdb should be passing something like "ChainMap(frame.f_locals,
> frame.f_globals)" to the eval call as its global namespace when the current
> frame uses optimized local variable references? That way even lexically
> nested scopes inside the eval call will all be able to see the current
> local variables via dynamic name lookup, even though they still won't see
> them as lexical closure references.

That sounds intriguing, but I can't easily get it to work. I get either
"TypeError: globals must be a real dict; try eval(expr, {}, mapping)", when
I pass that for globals, or the same error as before, "NameError: name 'a'
is not defined", when I follow that advice and pass the ChainMap instance
as the locals. Plus it(ironically, perhaps :-) it screws up the output of
"p locals()".

--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20180705/e758210d/attachment.html>

More information about the Python-Dev mailing list