On Sun, Jul 12, 2020 at 7:36 PM Greg Ewing <greg.ewing@canterbury.ac.nz> wrote:
On 13/07/20 7:12 am, Larry Hastings wrote:
> I dimly recall a precedent where the
> presence of locals() in a function body affected code generation,

The presence of exec used to do that, which is why it was a
statement rather than a function. But I don't think locals()
ever did -- how would the compiler know that it was calling
the builtin locals function and not something else?

super() does something similar:

 >>> class A:
...   def super_locals(self):
...     super
...     return locals()
...   def superless_locals(self):
...     return locals()
...
>>> A().super_locals()
{'self': <__main__.A object at 0x000001FF53BCE6D8>, '__class__': <class '__main__.A'>}
>>> A().superless_locals()
{'self': <__main__.A object at 0x000001FF53BCE7B8>}

The compiler changes what local variables exist if there is a read from a variable named 'super', in order to support zero-argument super() calls. It presumably could do the same sort of thing for locals(). I don't think this is a good idea, since locals() is a debugging tool, and changing reality based on the presence of debugging calls may make life more difficult for the user.

-- Devin