[Python-Dev] PEP 572 semantics

Steve Dower steve.dower at python.org
Wed Jul 4 20:20:46 EDT 2018


On 04Jul2018 1518, Tim Peters wrote:
> The only new thing is specifying the scope of `a`, where "local to f"
> means exactly the same thing as for any other name local to a function
> today.  So far as the PEP semantics go, it doesn't even matter whether
> an implementation _does_ implement some form of closure as such.  It
> just has to provide the visible semantics of _lexically_ nested scopes
> with indefinite extent, by whatever means it likes best.  That's what
> "local to f" means (and has meant all along - well, since lexically
> nested scopes were first introduced).

In that case, please provide more examples of how it should work when
the assignment expression appears to define a variable in a scope that
is not on the call stack.

Whether intentional or not, there will be changes to how and when names
are resolved. The specification should provide enough information to
determine the preferred behaviour, so we can tell the difference between
intention changes and implementation bugs.

For example, what should be returned from this function?

>>> A = 0
>>> def f(x):
...     if x:
...         [A := i for i in [1]]
...     return A

As far as I can tell, the closest current equivalent will not compile:

>>> A = 0
>>> def f(x):
...     if x:
...         def g():
...             nonlocal A
...             A = 1
...         g()
...     return A
...
  File "<stdin>", line 4
SyntaxError: no binding for nonlocal 'A' found

Is this the equivalent behaviour you want? Or do you want an
UnboundLocalError when calling f(0)? Or do you want the global A to be
returned? How should we approach decision making about these cases as we
implement this? The PEP does not provide enough information for me to
choose the right behaviour here, and I argue that it should.

Cheers,
Steve


More information about the Python-Dev mailing list