[Python-ideas] Trial balloon: adding variable type declarations in support of PEP 484

Steven D'Aprano steve at pearwood.info
Thu Aug 4 09:29:44 EDT 2016


On Thu, Aug 04, 2016 at 10:37:33PM +1000, Nick Coghlan wrote:

> I wonder if there's some way we could make that new statement form
> trigger the following runtime behaviour:
> 
>     a : int
>     a # This raises a new UnboundNameError at module scope,
> UnboundLocalError otherwise

Why wouldn't it raise NameError, as it does now?

I understand that `a: int` with no assignment will be treated as a no-op 
by the interpreter.

a: int = 0

will be fine, of course, since that's assigning 0 to a.


> Otherwise we're at risk of allowing thoroughly confusing runtime behaviour like:
> 
>     >>> a = "Not an int"
>     >>> def f():
>     ...     # a: int would go here
>     ...     print(a) # This should really fail
>     ...
>     >>> f()
>     Not an int

I would expect that the type-checker will complain that you're declaring 
a local variable "a" but there's no local "a" in the function. If the 
checker isn't that smart, I expect it would complain that "a" is set to 
a string, but declared as an int. Either way, the type-checker ought to 
complain.



-- 
Steve


More information about the Python-ideas mailing list