Skip to main content

Doctests: Should you use them in every function

· 2 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

So I’ve been thinking lately about testing strategies again, and one question came up that I kept circling back to: does every function in my Python codebase need to have a doctest?

ctest. But — and this is important — every public function that’s designed to be reused, or exposed in some way (via an API or SDK or CLI) should have some form of executable example, whether that’s a doctest or a regular unit test. Otherwise, the doc is just speculation. I mean, on one hand, doctests are elegant. They sit right in your docstring, they double as documentation and tests, and they’re super useful for small utility functions or places where an example is easier to grasp than a formal test case. But when I actually went through a few modules in my app and imagined writing a doctest for every function... it felt off. ment.” It’s a great mindset when you’re building reusable libraries — especially those consumed by others — but not as useful in large app codebases with hundreds of internal services and handlers. So now I mostly use doctests for helpers, utility libraries, and example-heavy code (like algorithms or conversion tools). Part of the problem is that not all functions are created equal. There are simple pure functions — like slugify(text) or is_valid_email(email) — that are deterministic and easy to test with one-liner examples. These are ideal for doctests. You write a quick:

>>> is_valid_email("<test@example.com>")doctest/>

and that’s it. It documents and validates the behavior in one shot. But So in the end — no, not every function needs a doctest. But when the function is pure, small, and its behavior is part of its documentation, a doctest is perfect. Otherwise, stick to classic tests.