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

Steven D'Aprano steve at pearwood.info
Sat Aug 16 07:04:33 CEST 2014


Some people like the epydoc-style convention of putting type annotations 
in docstrings:

[...]
> >>         def demo(self, a, b, c):
> >>             """
> >>             This function returns the product of a, b and c
> >>             @type self: SimpleEquation
> >>             :param a: int - The first number
> >>             :param b: int
> >>             :param c: int - The third number should not be zero and should
> >> also
> >>                 only be -1 if you enjoy carrots (this comment spans 2 lines)
> >>             :return: int
> >>             """

One issue I haven't see raised is that annotations are available at 
runtime, whereas docstrings may not be. (The -OO switch removes 
docstrings.) A linter may be able to parse the docstrings at compile 
time before the docstrings are discarded, or it may not, but using 
docstrings means the information is not always available for 
introspection at runtime. I think that's a major disadvantage.

Although I admit I don't always remember to test my code using -O and 
-OO, I do try very hard to do this and I have found bugs in my code from 
doing so. I think anything which makes testing -O and -OO modes harder 
is a bad thing.

[Quoting Barry Warsaw]
> docstrings
> naturally live right after the function signature (indeed, or it wouldn't get
> stuffed into __doc__), so it's always close to the source.  That makes it
> quite easy for the third party human reader, but also for the author to keep
> up-to-date.

*Close to the source* is not the same as *part of the source*. In the 
example above, the difference is as high as eight lines, compared to 
zero:

    # Function annotations
    def demo(self, a:int, b:int, c:int)->int:


Using docstring annotations splits the information about parameters into 
two places. Those two places might be close, but there are still two 
sources of ultimate truth instead of one. You have the name of the 
parameter in the parameter list, and the type of the parameter inside 
the docstring separated by some arbitrary number of lines of code.


-- 
Steven


More information about the Python-ideas mailing list