We can indicate the types of function parameters using docstring in python:
def f1(a):
"""
:param a: an input.
:type a: int
:return: the input integer.
:rtype: int
"""
return a
For f1
, autodoc generates the following document:
fun1(a)
Parameters : a (int) – an input.
Returns : the input integer.
Return type: int
In python 3, the types can be indicated by type hint as well:
def f2(a: int):
"""
:param a: an input.
:return: the input integer.
:rtype: int
"""
return a
When we run autodoc, it puts the type by the parameter declaration, but not in the description:
f2(a: int)
Parameters : a – an input.
Returns : the input integer.
Return type: int
Would it be possible to generate the documentation as f1
using annotation instead of docstring? I'm using python 3.6. Thank you!
What should a docstring look like? The doc string line should begin with a capital letter and end with a period. The first line should be a short description. If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.
Type hints improve IDEs and linters. They make it much easier to statically reason about your code. Type hints help you build and maintain a cleaner architecture. The act of writing type hints forces you to think about the types in your program.
Public methods (including the __init__ constructor) should also have docstrings. A package may be documented in the module docstring of the __init__.py file in the package directory. String literals occurring elsewhere in Python code may also act as documentation.
Introduction to Type Hints As the code base gets larger, type hints can help to debug and prevent some dumb mistakes. If you're using an IDE like PyCharm, you'll get a warning message whenever you've used the wrong data type, provided you're using type hints.
Not yet, from what I'm aware Sphinx yet doesn't support this. The bug referenced in a comment was about the representation of the type-hints and not their positioning.
I do know there's currently an extension for Sphinx that takes care of this for you though, called sphinx-autodoc-typehints. You could probably use that for the time being.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With