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

Stephen J. Turnbull turnbull.stephen.fw at u.tsukuba.ac.jp
Tue Sep 6 14:11:21 EDT 2016


Mark Shannon writes:

The problem with using the term "variable" is that it is not vague. Variables in python have well defined scopes and lifetimes.

Sure, but hints are not well-defined by Python (except the syntax, once PEP 526 is implemented). A hint is something that the typechecker takes note of, and then does whatever it pleases with it.

So can we do the practical thing here and agree that even though the type hint on a variable is constant, what the typechecker does with that type hint in different contexts might change?


The rest is tl;dr (why I want type hints on variables, and why the term "annotating expressions" leaves me cold).

I don't see how you can interpret

z: complex = 1.0

without a notion of annotating the variable. The RHS is clearly of float type, and Python will assign a float to z. What's going on here? Maybe this:

from math import exp

z: complex = 1.0
print(exp(z))

==> "MyPy to Steve! MyPy to Steve! You are confused!"

Maybe "math" was a typo for "cmath". Maybe "complex" was a premature generalization. Maybe you wouldn't want to hear about it ... but I would. I think. Anyway, to find out if I really want that or not, I need a notion of hinting the variable.

But: "although practicality beats purity". Like everybody else, I want a typechecker that minds its manners and says nothing about

from math import exp

z: complex = 1.0
try:
    print(exp(z))
except TypeError:
    print("Oh well, complex is better than complicated.")

Finally, the notion of annotating expressions is incoherent:

# Annotating (sub)expressions: the more the merrier!
(x) : bool = (((y): int + (z): float) / (w): complex): quarternion
# Ooh, an expression with no past and no future.  Annotate it!
(y + z) / w: quarternion

Noone has any intention of annotating expressions AFAICS -- people who talk about that really mean annotating the value of the expression on the RHS, but since it will always be on the RHS of an assignment, it's equivalent to annotating the value of the target on the LHS.



More information about the Python-Dev mailing list