[Python-Dev] Type hints -- a mediocre programmer's reaction
Chris Kaynor
ckaynor at zindagigames.com
Mon Apr 20 21:03:08 CEST 2015
On Mon, Apr 20, 2015 at 11:30 AM, Harry Percival <hjwp2 at cantab.net> wrote:
> My first reaction to type hints was "yuck", and I'm sure I'm not the only
> one to think that. viz (from some pycon slides):
>
> def zipmap(f: Callable[[int, int], int], xx: List[int],
> yy: List[int]) -> List[Tuple[int, int, int]]:
My opinion of type hints is: they are great inline, when they are
simple. Cases like (I know its not a real-world case, but there are
plenty of similarly simple functions):
def add(a: int, b: int) -> int:
are fine. When you get more complicated examples, especially when they
involve complex types (list, tuple, callable, etc). In such cases, it
may make sense to predefine a type (I believe the typehints PEP
supports some form of typedef - I think just a simple assignment) and
use that instead of the full type name. This will generally make the
function definition MUCH easier to read.
> That sounds like the best of both worlds to me.
> - .py files stay beautiful, concise, and easy to read.
> - beginners don't have to worry about wading through type definitions when
> they find themselves browsing someone else's source
> - type information is available to the linters and static file checkers, so
> we get all the benefits.
>
> Sounds great right? Everybody will be happy! So let's nail it down! If I
> was in charge, here's what I'd do:
>
> * standardise the syntax for type hints in 3.5, as per PEP484
> * but: recommend the use of stub files as the preferred place to store hints
> * and: deprecate function annotations in the core language
> * remove them from the core language altogether in 3.6
The main drawback of using a stub file is that it is much more likely
to end up out-of-date, and thus useless at best, than if the types are
defined inline. The same issue applies to various alternative
proposals such as having the typehints in decorators, but to a lesser
degree. The same issue also applies to general comments as well.
I would say there are a few major reasons to use stub files:
1) You cannot put the annotations in the source, probably either
because the module is a C library, or you must support versions which
do not support annotations.
2) You must use annotations for other purposes.
3) The annotations are particularly complicated, and you cannot
provide nice names for the various types (likely, because the types
are just very difficult to name, such as in the zipmap example, though
that one might be easier in a more specific context).
Outside of those specific reasons, I would vastly prefer any
annotations to be included in the source, where they are much more
likely to be updated, rather than in a separate file, where they will
likely be forgotten.
More information about the Python-Dev
mailing list