Internal documentation

Docstrings and type hints comments

Python utilises docstrings and type hints to document code. Docstrings are multi-line strings that provide information about modules, classes, functions and methods. Type hints, on the other hand, allow for specifying the expected types of function parameters and return values.

Docstrings and type hints are used in Python:

  • at the top of each file
  • before classes, functions and methods
  • before variables and properties
  • before interfaces and constants.

Use """ followed by a space to start a docstring comment and """ to end it.

  • Put a docstring comment at the top of each file describing its contents, author and copyright date.
  • Put a docstring comment above each class to describe what it is for, and how to use it.
  • Put a docstring comment above each function to describe what it is for, and how to use it.
  • Optionally, provide docstrings for variables, particularly if their purpose is not immediately clear from the variable name.
  • Put a single line or multi-line comment above each significant block of code to describe what it is doing (e.g. what data is collecting).

Only comment parts of your code that are important, interesting or not obvious.

Use correct grammar and spelling in comments.

You can read more about Python docstring conventions at PEP257.

Type hints

Python allows you to provide type hints for function parameters and return values, although they are not enforced at runtime. This helps document the expected types of values.

Example:

def my_function(param: int) -> str:
"""
This function does something.

Parameters:
param (int): Description of param.

Returns:
str: Description of return value.
"""

# Function body

These practices help developers understand how to use your code effectively and provide helpful hints for integrated development environments (IDEs) and static analysis tools.