[Python-ideas] Trial balloon: adding variable type declarations in support of PEP 484
Alexander Belopolsky
alexander.belopolsky at gmail.com
Thu Aug 4 12:44:11 EDT 2016
On Thu, Aug 4, 2016 at 12:15 PM, Guido van Rossum <gvanrossum at gmail.com> wrote:
> It will do exactly the same as
>
> a = None
> def f():
> if False: a = ...
> a
>
> This raises UnboundLocalError (a subclass of NameError).
That's what I expected. Moreover, it looks like there is a precedent
for such behavior:
$ python3 -O
>>> a = None
>>> def f():
... if __debug__: a = ...
... a
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in f
UnboundLocalError: local variable 'a' referenced before assignment
>>> dis(f)
3 0 LOAD_FAST 0 (a)
3 POP_TOP
4 LOAD_CONST 0 (None)
7 RETURN_VALUE
(Note that the if statement is optimized away.)
BTW, a: int looks like an "incomplete" assignment to me. It's a
statement that under-specifies a: gives it a type, but not a value.
Visually, ':' is a shorter version of '=' and a half of the venerable
Pascal's ':='. It all makes sense to me, but your milage may vary if
your first language was JavaScript rather than ALGOL. :-)
More information about the Python-ideas
mailing list