Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Writing and Testing Examples

To learn more about doctest, check out Python’s doctest: Document and Test Your Code at Once.

00:00 Write Examples and Test Them Using Doctest. Adding examples to your docstrings is good practice. Doing this clarifies how to use the functions, and when you stick to a specific format, you can even test your code examples using Python’s doctest module.

00:20 Google suggests adding examples to your docstring under a heading called "Examples:", which works well for running doctests and building your documentation using MkDocs.

00:31 Head back into and add example use cases to your function docstrings. Add a section called "Examples:" and with an extra indentation level, add example calls to the function you are documenting.

00:45 You provide the input after the default Python REPL prompt (>>>), and you put the expected output in the next line. These examples will render well in your auto-generated documentation and add context to your function. You can even test them!

01:01 Verify that your functions work as expected by executing the file using Python’s doctest module. Here’s the test running on Windows …

01:17 and on macOS or Linux.

01:25 If you don’t see any output, then all of the tests passed. This is great, as you’ve successfully added doctests to your function. If you change one of the numbers in an example and run the test again, then you’ll see what a failing test looks like.

01:50 Don’t forget to change the example back to the correct value. Revisit all of your functions and add doctests in the same way as you did for add() earlier on.

03:01 When you finish writing doctests for all your functions, run the tests using doctest to confirm that all of the tests pass.

03:13 You’ve expanded the scope of your docstrings to be more comprehensive and valuable. To improve your codebase even more, in the next section, you’ll add type hints to your function definitions.

Become a Member to join the conversation.