Quote:suppose my function returns a 2-list or 2-tuple to the caller. documenting this function needs to refer to the item that would be accessed with [1]. should the text in this documentation refer to this as the "2nd" item or the "1st" item or the "[1]" item?
Yes, this was a problem before typehints were invented.
Now we can document code, giving the IDE better context and static type checking with mypy.
Often document strings hold too much information about types of arguments. Using instead typehints will prevent the information bloat in the docstring.
from typing import NamedTuple
class Result(NamedTuple):
"""
This instance is a result ...
"""
a: int
b: str
def some_function(iterations: int, name: str) -> Result:
"""
This function does nothing useful
"""
return Result(42, 23)
if __name__ == "__main__":
res = some_function(None, None)
a, b = some_function(1, "foo")
b = some_function(1, "foo")
If you put this code in your IDE, the IDE should detect the errors in the code.
For example Result expects one int and one str, but in the function call it's called with two integers.
I named this example epl_test.py. Don't ask why..
Output:
andre@andre-GP70-2PE:~$ python epl_test.py
andre@andre-GP70-2PE:~$
No error? All fine?
Output:
andre@andre-GP70-2PE:~$ mypy epl_test.py
epl_test.py:16: error: Argument 2 to "Result" has incompatible type "int"; expected "str"
epl_test.py:20: error: Argument 1 to "some_function" has incompatible type "None"; expected "int"
epl_test.py:20: error: Argument 2 to "some_function" has incompatible type "None"; expected "str"
epl_test.py:22: error: Incompatible types in assignment (expression has type "Result", variable has type "str")
Found 4 errors in 1 file (checked 1 source file)
andre@andre-GP70-2PE:~$
The corrected version:
from typing import NamedTuple
class Result(NamedTuple):
"""
This instance is a result ...
"""
a: int
b: str
def some_function(iterations: int, name: str) -> Result:
"""
This function does nothing useful
"""
return Result(42, "23")
if __name__ == "__main__":
a, b = some_function(1, "foo")
Output:
andre@andre-GP70-2PE:~$ python epl_test2.py
andre@andre-GP70-2PE:~$ mypy epl_test2.py
Success: no issues found in 1 source file
I'm very lazy of writing docstrings, but I use regularly typehints to document my code better. So later I come back and see direct, which input/output types are required and the docstring holds only information, what the function does with some additional info about arguments, but not their types. The types should not declared in the docstring, if the type annotation is used. Otherwise, after a code change the comment/docstring could be misleading.
We all know this situation. The comment or doctstring says a function will return
True
and in reality the function returns
False
.