In Python, documentation of code through docstring has been encouraged since the earliest versions. With the introduction of Python 3.5 (PEP 484), type annotations (type hints) were added to improve readability and enhance the support for type analyzers (e.g., mypy, pyright, etc.). Thus, documentation and typing can be combined directly in the function and class definitions.
Without type annotations, it is difficult to quickly understand what a function is operating on and what to expect from it. A lack of good docstring leads to misunderstandings of the interface and usage errors. Incorrect use of type hints or docstrings hampers static analysis and reduces code maintainability.
Use multi-line docstrings to document the purpose of the function, parameters, and its result, as well as type hints for explicitly specifying the types of arguments and return values.
Code example:
def add_numbers(a: int, b: int) -> int: """ Adds two integers and returns the result. :param a: First addend, int :param b: Second addend, int :return: Sum, int """ return a + b
Key features:
Can type annotations affect program execution?
No. Type annotations (type hints) are not checked by the Python interpreter during execution and serve only for analyzers and IDEs, as well as for auto-generating documentation. They do not lead to runtime errors and are always optional.
Can type annotations be used to restrict the values of a parameter?
No. Specifying a type, for example, x: int does not prevent the passing of a value of another type in practice. For this, runtime checks (assert/isinstance) can be used, but not type hints — they are not automatically verified.
Can comments # type: ... be used instead of annotations? When is this necessary?
Yes, it is allowed if compatibility with Python 2 or legacy codebases is needed. For example:
def foo(x, y): # type: (int, str) -> bool pass
This is understood by mypy and similar tools alongside modern syntax, but in new projects, it is better to use standard annotations.
In a large project, functions are not equipped with docstring and type hints at all — the developer spends a lot of time studying and debugging, often making mistakes with types and the purpose of input data.
Pros:
Cons:
All public functions have comprehensive docstrings and correct type hints, which allows IDEs and analyzers to quickly find type errors and automatically generate API documentation.
Pros:
Cons: