Adding Module Docstrings
00:00 Add Module Docstrings. Python docstrings aren’t restricted to functions and classes. You can also use them to document your modules and packages, and mkdocstrings will extract these types of docstrings as well.
00:16
You’ll add a module-level docstring to calculations.py
and a package-level docstring to __init__.py
to showcase this functionality. Later, you’ll render both as part of your auto-generated documentation.
00:32
The docstring of calculations.py
should give a quick overview of the module and then list all the functions that it exports, together with a one-line description of each function.
01:14 You may notice that this docstring contains Markdown formatting. MkDocs will render it to HTML for your documentation pages. Just as for function docstrings, you can also add usage examples for your module to the docstring.
01:59 You can test these examples as before by running doctest on the module.
02:11 Try swapping one of the return values to see the doctest fail,
02:24
and then fix it again to ensure your examples represent your module’s functionality. Finally, you’ll also add a package-level docstring. You add these docstrings to the top of your package’s __init__.py
file before any exports that you’d define there. In this example package, you’ll export all functions defined in calculations.py
, so __init__.py
won’t contain any Python code aside from the docstring.
02:52
In your Python project, you may want to define which objects your package exports, and you’d add the code below the doctring for your package. Open your empty __init__.py
file and add the docstring for your calculator
package, as seen on-screen.
03:13
This adds a short description of the package and the module it contains to the top of your __init__.py
file. If your package was going to export more modules and subpackages, you’d also list them here.
03:27 After writing the docstring for the package, you’ve completed all the docstrings that you wanted to add to your code. Your Python project’s source code is well documented using docstrings and type hints, and it even contains examples that you can run as doctests.
03:43 You’ve finished this element of your project’s code documentation, and it’ll always stick with your code. You’re now ready to raise the bar for your project’s documentation by building user-friendly documentation pages using MkDocs, and that’s what you’ll be looking at in the next part of the course.
Become a Member to join the conversation.