Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can type hint in python 3 be used to generate docstring?

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!

like image 568
Jinho Choi Avatar asked Feb 16 '17 19:02

Jinho Choi


People also ask

How do I create a docstring in Python?

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.

What is the point of Python type hinting?

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.

Should __ init __ have a docstring?

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.

What are reasons for using type hinting?

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.


1 Answers

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.

like image 72
Dimitris Fasarakis Hilliard Avatar answered Oct 24 '22 09:10

Dimitris Fasarakis Hilliard