Reputation: 761
When using google style docstrings and type annotations there's a double up of the type hints.
Is there any community consensus on how to avoid this?
Annoying double up of types:
def sum(a: int, b: int) -> int:
""" blah blah
Args:
a (int): value 1
b (int): value 2
Returns:
int: summed values
"""
return a + b
Should types be left out of the docstring like this?
def sum(a: int, b: int) -> int:
""" blah blah
Args:
a: value 1
b: value 2
Returns:
summed values
"""
return a + b
I haven't seen anyone else mention this, but I can't be the only one unsure about the best approach here.
Upvotes: 25
Views: 13146
Reputation: 346
Yes, you only need the type hints OR the annotations in the Args and Returns, not both.
References
According to the Google Python Style Guide: "The description should include required type(s) if the code does not contain a corresponding type annotation."
The Sphinx Docs also encourage this in their example code:
def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
"""Example function with PEP 484 type annotations.
Args:
param1: The first parameter.
param2: The second parameter.
Returns:
The return value. True for success, False otherwise.
"""
Upvotes: 22
Reputation: 71454
This is very much IMHO, but I don't think enumerating all the parameters in the docstring has a lot of value if you have decent names and type annotations.
def sum(a: int, b: int) -> int:
"""Returns the result of adding the inputs together."""
return a + b
is more than adequately clear IMO. In real life with this specific example I'd probably do:
def sum(a: int, b: int) -> int:
"""Does exactly what it says."""
return a + b
Since the parameters are two int
s, the result is another int
, and the name of the function is sum
which is a perfectly ordinary English word that means "the thing you get when you add other things together", I don't think any further explanation is necessary (other than perhaps a confirmation that this isn't a trick).
Upvotes: 3