Search code examples
pythonpython-typingdocstring

python: how to use type annotations and docstring formats together


Now that we have type annotations in Python, I'm wondering how to document code with type annotations AND docstring formats.

Specifically, it seems redundant to specify the argument types as an annotation AND :type: in the docstring, as in the restructured text format example below. The descriptions in the docstring format is still useful.


def my_function(db: Session, name: str) -> str:
   """Some function

   :param db: a database connection
   :type db: Session
   :param name: some name
   :type name: str
   :return: return something
   :rtype: str
   """

One option might be to write the function like this:


def my_function(db: Session, name: str) -> str:
   """Some function

   :param db: a database connection
   :param name: some name
   :return: return something
   """

How do I write DRY docstrings for code with type annotations, so that it is most compatible with IDE type inference tools (i.e. VSCode), linters, mypy, auto documentation tools (i.e. Sphynx), and other community-based tools for generating and introspecting documentation?


Solution

  • Just use the function signature. Don't document it too.

    Any documentation tool worth its salt will parse the function signature, including types, and show that, so :type foo: would indeed be redundant.

    For sphinx see the autodoc extension, especially here