[Python-Dev] PEP 526 ready for review: Syntax for Variable and Attribute Annotations (original) (raw)

Guido van Rossum guido at python.org
Tue Aug 30 23:03:00 EDT 2016


On Tue, Aug 30, 2016 at 7:44 PM, Jack Diederich <jackdied at gmail.com> wrote:

+0. We should try and be consistent even if this is a thing I don't want. And trust me, I don't!

No problem. You won't have to!

That said, as long as pro-mypy people are willing to make everyone else pay a mypy reading tax for code let's try and reduce the cognitive burden.

* Duplicate type annotations should be a syntax error. Duplicate annotations aren't possible in functions so that wasn't an issue in 484. 526 makes some things syntax errors and some things runtime errors (for good reason -- function bodies aren't evaluated right away). Double-annotating a variable is something we can figure out at compile time and doing the double annotating is non-sensical so we should error on it because we can.

Actually I'm not so sure that double-annotating is always nonsensical. In the mypy tracker we're seeing some requests for type inference that allows a variable to be given another type later, e.g.

x = 'abc'
test_func(x)
x = 42
another_test_func(x)

Maybe there's a use for explicit annotations too. I would rather not get in the way of letting type checkers decide such semantics.

* Dissallowing annotations on global and nonlocal Agreed, allowing it would be confusing because it would either be a re-definition or a hard to read annotation-at-a-distance.

* Where annotations live It is strange to allow modules.annotations and MyClass.annotations but not myfunc.annotations (or more in line with existing function implementations a myfunc.code.coannotations). If we know enough from the syntax parse to have func.code.covarnames be known then we should try to do that with annotations. Let's raise a SyntaxError for function body annotations that conflict with same-named variables that are annotated in the function signature as well.

But myfunc.annotations already exists -- PEP 3107 puts the signature annotations there. The problem with co_annotations is that annotations are evaluated (they can be quite complex expressions, e.g. Optional[Tuple[int, int, some_mod.SomeClass]]), while co_varnames is just a list of strings. And code objects must be immutable. The issue with rejecting duplicate annotations so sternly is the same as for the previous bullet.

I did C++ for years before I did Python and wrote C++ in many languages (including Python). So ideally I'm -1000 on all this stuff for cultural reasons -- if you let a C++ person add types they will for false comfort. But again, I'm +0 on this specific proposal because we have already gone down the garden path.

As long as you run mypy the comfort shouldn't be false. (But your starting with C++ before Python explains a lot. :-)

-Jack

-- --Guido van Rossum (python.org/~guido)



More information about the Python-Dev mailing list