[Python-ideas] Proposal: Use mypy syntax for function annotations

Stefan Behnel stefan_ml at behnel.de
Thu Aug 14 19:37:55 CEST 2014


Guido van Rossum schrieb am 13.08.2014 um 21:44:
> Yesterday afternoon I had an inspiring conversation with Bob Ippolito (man
> of many trades, author of simplejson) and Jukka Lehtosalo (author of mypy:
> http://mypy-lang.org/). Bob gave a talk at EuroPython about what Python can
> learn from Haskell (and other languages); yesterday he gave the same talk
> at Dropbox. The talk is online (
> https://ep2014.europython.eu/en/schedule/sessions/121/) and in broad
> strokes comes down to three suggestions:
> 
>   (a) Python should adopt mypy's syntax for function annotations
> [...] proposal (a) feels right to me.

FWIW, Cython currently understands these forms of function argument
annotations in Python code:

    x: dict
    x: {"type": dict}
    x: {"type": "dict"}
    x: {"ctype": "long double"}

The "ctype" values that are usable here obviously only include those that
can be converted from and to Python types, e.g. no arbitrary pointers.

It'd be nice to have a way to declare container item types, but that's
never really been a priority in the Cython project so far. Declaring
protocols, OTOH, is pretty useless for a compiler, as it's obvious from the
code which protocols are being used on a given value (iteration, item
access, etc.).

It's clear that restricting everything to one kind of annotation isn't
enough, as there are use cases for a mix of different type systems, Python
itself plus at least C/C++ in CPython and Cython, Java in Jython, C# in
IronPython, plus others that people might want to interface with. C/C++ are
generally interesting, for example, also for .NET or JVM users.

Although I wasn't very impressed by Bob Ippolito's talk at EuroPython, I'm
generally not opposed to type annotations to provide 1) additional contract
information for libraries, 2) documentation, 3) better static analysis or
4) type hints for compilers. But these are actually quite different use
cases that may each suggest a different strictness in the type
declarations. For 3) and 4), function signatures aren't enough and should
be accompanied by declarations for local variables. 4) should also support
additional type systems for language integration. But 1) and 2) aren't
completely overlapping either. 1) would need declarations that can be used
for hard type checking, whereas 2) can be much more relaxed, generic and
incomplete. Trying to get all of these under one umbrella might not be a
good idea, but letting people add three different annotations for each
function argument definitely isn't either.

Stefan




More information about the Python-ideas mailing list