[Python-Dev] Do PEP 526 type declarations define the types of variables or not?

Greg Ewing greg.ewing at canterbury.ac.nz
Mon Sep 5 18:16:37 EDT 2016


Mark Shannon wrote:

> Unless of course, others may have a different idea of what the "type of 
> a variable" means.
> To me, it means it means that for all assignments `var = expr`
> the type of `expr` must be a subtype of the variable,
> and for all uses of var, the type of the use is the same as the type of 
> the variable.

I think it means that, at any given point in time, the
value of the variable is of the type of the variable or
some subtype thereof. That interpretation leaves the
type checker free to make more precise inferences if
it can. For example, in...

>     def foo()->int:
>         x:Optional[int] = bar()
>         if x is None:
>             return -1
>         return x

...the type checker could notice that, on the branch
containing 'return x', the value of x must be of type
int, so the code is okay.

-- 
Greg



More information about the Python-Dev mailing list