[Python-Dev] Type hints -- a mediocre programmer's reaction
Guido van Rossum
guido at python.org
Mon Apr 20 22:41:53 CEST 2015
On Mon, Apr 20, 2015 at 12:51 PM, Nikolaus Rath <Nikolaus at rath.org> wrote:
> On Apr 20 2015, 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]]:
> >
> > arg. and imagine it with default arguments.
>
> This is indeed ugly as hell and I certainly would not want to see this
> in any Python file I'm working with.
>
> However, I always assumed that whatever tools consume these annotations
> are expected to be good enough at automatic type inference that
> something like this would never be necessary?
>
> In practice, I would hope that the above simplifies to
>
> def zipmap(f, xx: List[int], yy: List[int]):
>
> because (just picking a probably buggy random implementation)
>
> zz = [] # --> z must be List[A]
> for i in range(min(len(xx), len(yy))):
> x = xx[i] # --> x must be int
> y = xx[i] # --> y must be int
> z = f(x,y) # --> f must be Callable[(int,int], B]
> zz[i] = (x,y,z) # --> A must be Tuple[int,int,B]
>
> return zz # --> return value must be List[Tuple[int,int,B]]
>
> it doesn't catch that B = int, but I think that's acceptable.
>
>
> Is this not the case? Are we really expecting people to write stuff like
> the above?
>
Jukka (mypy's author) believes that specifying full annotations will catch
more bugs, and makes the error messages easier to understand -- in practice
when you let the type inferencer run free it will often infer bizarre union
types or other complex forms, and the errors may well appear in the wrong
spot. This is a common issue with type inferencing, and anyone who has
tried to learn Haskell (or C++ :-) has plenty of experience with such
errors.
The good news is that I don't actually expect people to have to write or
even read stuff like the above; the example was quoted out of context. In
code that the typical (mediocre :-) programmer writes, argument types won't
be more complex than some built-in primitive type (e.g. int or str) or a
List of primitive types, or perhaps a user-defined class or List of such.
And you can always leave the annotation out if you find yourself fighting
the type checker -- it will default to Any and the type checker will just
shut up. That's the beauty of gradual typing (and it differs greatly from
strict typing as seen in Haskell or C++).
--
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20150420/0957a1b4/attachment-0001.html>
More information about the Python-Dev
mailing list