Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: docstrings and type annotations

Having a function like:

def foo(x: int) -> float:
    return float(x)

I would like to use a NumPy-like docstring like the following:

def foo(x: int) -> float:
    """
    Parameters
    ----------
    x
        Input parameter

    Returns
    -------
    The output value.
    """
    return float(x)

Note that:

  • I do not want to specify the parameter type again.
  • I do not want to specify the return type again.
  • I would like that extension to be able to read the annotated types (and write them in the generated HTML documentation).

Is there a Sphinx extension that supports that? Would you recommend another syntax?

like image 687
Peque Avatar asked May 30 '17 15:05

Peque


People also ask

What are type annotations in Python?

What Are Type Annotations? Type annotations — also known as type signatures — are used to indicate the datatypes of variables and input/outputs of functions and methods. In many languages, datatypes are explicitly stated. In these languages, if you don't declare your datatype — the code will not run.

What are the docstrings in Python?

A Python docstring is a string used to document a Python module, class, function or method, so programmers can understand what it does without having to read the details of the implementation. Also, it is a common practice to generate online (html) documentation automatically from docstrings.

What are the three types of docstrings?

Docstrings can be further broken up into three major categories: Class Docstrings: Class and class methods. Package and Module Docstrings: Package, modules, and functions. Script Docstrings: Script and functions.

What is the difference between docstring and comments in Python?

Comments in Python improve the readability of the program, it explains the code in a language that is easy to understand whereas docstrings describe what the code does, it does not explain how the code works.


1 Answers

Standard extension is autodoc. Napoleon extension supports Google- and NumPy-style docstrings.

like image 128
phd Avatar answered Oct 06 '22 11:10

phd