Python·100 questions

How to write docstrings correctly?

Answer

Correctly writing documentation for functions and classes in Python, known as docstrings, is a sign of a professional approach to development and significantly simplifies code maintenance for the entire team. Documentation should answer the main questions: what task this piece of code solves, what arguments it accepts, what it returns as a result of its work, and what exceptions it can raise when abnormal situations occur.

To achieve maximum readability and consistency in a project, you must choose one of the established styling standards, such as Google Style, NumPy Style, or the PEP 257 standard. Regardless of the chosen style, the first line should always contain a brief and concise description of the function's purpose in the imperative mood, followed by a blank line and a detailed description of the parameters.

When drafting a high-quality function description, it is recommended to follow this structure.

Start with a brief summary on the first line, ending with a period.
Describe each function argument, indicating its expected data type and purpose in the Args section.
Describe the return value and its type in the Returns section so the developer understands the output data structure.
List possible exceptions in the Raises section if the function explicitly throws errors for invalid input data.
Add a small practical usage example in the Examples section, which can be automatically tested using the doctest module.

Adhering to a single documentation standard within the team eliminates the need to guess function behavior, improves autocompletion in modern code editors and IDEs, and facilitates the automatic generation of technical documentation for the entire project.

Was this answer helpful?

More questions in this topic

Related questions from other topics