[Python-ideas] PEP 484 (Type Hints) -- first draft round

Steven D'Aprano steve at pearwood.info
Sat Jan 17 07:51:19 CET 2015


On Fri, Jan 16, 2015 at 08:57:41PM -0500, Cem Karan wrote:

> If we're using decorators for the annotations, why not use them for 
> the typing as well?  E.g.,
> 
> @typing.type(a, int)
> @doc.doc(a, "some doc")
> def f(a):
>     pass
> 
> This would be the equivalent of:
> 
> def f(a: {"typing.type": int, "doc.doc": "some doc"}):
>     pass

Decorators are a second-class solution to the annotation problem, 
because they require you to repeat the variable name in at least two 
places.

In the past I have strongly defended the idea that type-hinting 
annotations need to co-exist with other uses for annotations. By this I 
mean that there should be a simple way for the author of a module who 
uses annotations for something else to flag that module, or parts of the 
module, so that the type-checker skips it.

There is no good way to have multiple uses of annotations be used in the 
same function. You have suggested using a dict, but what of the module 
that wants to give a completely different meaning to dicts as 
annotations? Your interpetation of annotations is not compatible with 
that module. Like multiple inheritence, multiple use of annotations is 
only possible if all parties cooperate and agree on semantics.

Besides, the more information you try to squeeze into the function 
parameter list, the more unwieldy, unreadable and ugly it gets.

Type-hinting was Guido's original motivation for introducing 
annotations, and there is no other use of annotations which has become 
popular or widespread enough to justify calling it a "standard use". So 
in the absense of any other standard use of annotations, I am 
comfortable with giving type-hints special status:

- whether type-checking is enabled by default or not, we understand that 
  annotations are primarily for type-hinting, and any annotations are to 
  be understood as type-hints by default;

- other uses for annotations are permitted, but it is up to the user to 
  flag the module/class/function so the type-checker skips it;

- no provision is made for mixing type-hints and arbitrary other uses in 
  the same annotation (in other words, if you want to use annotations 
  for type-hinting and Foo *at the same time*, you're on your own);

- but of course, nothing stops you from creating your own custom 
  annotation scheme that includes Foo + type-hints.

If some other use of annotations becomes wildly successful, then it 
may be worth rethinking the special status of type-hinting in the 
future.

If you want to interoperate with type-hinting, decorators may be a 
second-class solution, but they are a solution.


-- 
Steve


More information about the Python-ideas mailing list