PEP 526 - var annotations and the spirit of python

Steven D'Aprano steve+comp.lang.python at
Thu Jul 5 09:07:12 EDT 2018

On Thu, 05 Jul 2018 13:54:28 +0200, Antoon Pardon wrote:

> On 05-07-18 11:59, Steven D'Aprano wrote:
>> On Thu, 05 Jul 2018 17:34:55 +1200, Gregory Ewing wrote:
>>>> Indeed, that's often the best way, except for the redundant type
>>>> hint, which makes you That Guy:
>>>>     x: int = 0  # set x to the int 0
>>> But you've shown in an earlier example that such a hint is *not*
>>> always redundant
>> But it is redundant in *that* example. Your hint is not giving any more
>> information that what the reader, or type checker, can already infer.
> Yes it gives more information. Without the hint you can only interfere
> that it is an int at that point.

That would be utterly pointless:

 x = 3                  # infer x must be an int, but only at this point
 y = x + "Hello world"  # who knows what x is now? maybe it's okay

A type checker that did that would be a waste of time.

> IIUC, with the hint you can interfere
> it is supposed to be an int during its life time, not just at that
> point.


    Mypy considers the initial assignment as the definition
    of a variable. If you do not explicitly specify the type
    of the variable, mypy infers the type based on the
    static type of the value expression

This is not an innovation of Mypy. It's how type inference is supposed to 
work. If a particular type checker doesn't do that, it is doing it wrong.

Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson

More information about the Python-list mailing list