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

Mark Shannon mark at hotpy.org
Tue Sep 6 11:25:48 EDT 2016



On 05/09/16 23:16, Greg Ewing wrote:
> 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...

How does that differ from annotating the type of the expression?

>
>>     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.
>

The issue is not whether the checker can tell that the type of the 
*expression* is int, but whether it is forced to use the type of the 
*variable*. The current wording of PEP 526 strongly implies the latter.

Cheers,
Mark.


More information about the Python-Dev mailing list