Using the variable type annotation syntax as a placeholder in a nonlocal scope?

Terry Reedy tjreedy at udel.edu
Fri Dec 22 09:23:08 EST 2017


On 12/22/2017 8:53 AM, Kirill Balunov wrote:
> On Dec 20, 2017 22:43, "Kirill Balunov" <kirillbalunov at gmail.com> wrote:

>> Since PEP 526 -- Syntax for Variable Annotations
>> <https://www.python.org/dev/peps/pep-0526/>  was approved, in Python 3.6+
>> it is possible to provide type hint information in the form *x: int*,
>> also the PEP says "However, annotating a local variable will cause the
>> interpreter to always make it local to the scope and leaves the variable
>> uninitialized".

It is unitialized only if you do not initialize it.

>> Therefore in Python 3.6+ it is syntactically legal to
>> write:
>>
>> def outer():
>>      x: int
>>      def inner():
>>          nonlocal x
>>          x = 10
>>      inner()
>>      print(x)

Why would you write the above instead of

 >>> def f():
	x:int = 10
	print(x)
	
 >>> f()
10

>> while the above snippet is semantically more equivalent to:

More equivalent than what?

>> def outer():
>>      #x
>>      def inner():
>>          nonlocal x
>>          x = 10
>>      inner()
>>      print(x)
>>
>> Which is obviously a *SyntaxError: no binding for nonlocal 'x' found`*,
>> sorry for the pun. Also there is nothing said about this style in PEP 8 and
>> Python 3.6 docs. So should I consider this as a bug, or an implementation
>> detail (side effect), or a wart, or a feature?

I don't understand the question.  Maybe people on SO did not either.

-- 
Terry Jan Reedy




More information about the Python-list mailing list