Lesson · Idiomatic Python & Code Quality
Documentation
55 min readDocumentation
Documentation explains contracts, intent, examples, and non-obvious decisions. Good docstrings and type hints complement readable code rather than narrating every implementation detail.
Learning goals
- Read a docstring through
help()and__doc__, and explain what placement turns a string literal into a docstring. - Write a module docstring that states what the file is for and when to reach for it.
- Write function docstrings that record the contract (parameters, return value, raised exceptions, non-obvious decisions) without narrating the body.
- Explain what a type hint documents (the shape of values) and what it leaves unstated (units, semantics, side effects).
- Recognize documentation that has drifted from behavior and decide whether the docstring or the code needs the fix.
Mental model
Documentation is layered by the question it answers: the module docstring says what the file is for, class and function docstrings state their contracts, type hints state value shapes, and examples show the smallest real call. Each layer covers ground the others cannot, so a missing layer sends readers back to the source to reconstruct intent. Keeping docs close to behavior is the maintenance layer: prose that stopped matching the code misleads with authority.
Mental model
read it top to bottom
reader question: what is this file for? ↓ module docstring: purpose and scope what does this class or function promise? ↓ docstrings: contract, edges, exceptions type hints: value shapes that tools can check ↓ examples: the smallest runnable call, with its result
Core idea
Documentation is a contract surface, not a narration of the implementation: it tells a reader what a module, class, or function promises, what it expects, and where its edges are. Docstrings and type hints carry different parts of that contract, prose for intent and exceptions, annotations for value shapes, and both decay the moment behavior changes without them; keeping them close means either updating the prose or changing the code until the prose becomes true again.
Docstrings
A docstring is a string literal placed first in a module, class, function, or method body. Tools expose it through __doc__ and use it for generated documentation and interactive help.
Module docs
A module docstring is the first string literal in a file, before any imports or other statements, and it says what the module is for and when to use it. Tools read it through __doc__ and help(), and generated documentation sites use it as the entry page. Keep it short: purpose, scope, and any note that applies to every user of the module.
Function docs
A function docstring sits immediately below the def line and records the contract a caller needs: what the parameters mean, what the function returns, which exceptions it raises, and any non-obvious decision such as a normalization the caller might otherwise redo. It should state behavior, not narrate the body, since the body can change while the contract stays the same. Tools expose it through help() and __doc__.
Class docs
A class docstring appears immediately below the class line and describes what instances represent and how to create them, including any important attribute or invariant. Constructor parameters are often documented here or in __init__, and the docstring should state what the class guarantees, not the internal steps that provide the guarantee. Readers reach it through help() on the class.
Type hints as documentation
Type hints make value-shape expectations machine-readable and visible to readers, but they do not replace prose about semantics, units, side effects, or error behavior.
Examples
Examples in documentation are the smallest runnable calls that show how a unit is meant to be used, with real inputs and their expected results. A faithful example is precise enough to paste into a REPL and current enough that its output still matches, which is what makes it evidence that the documentation was tested. When an example goes stale, treat it as a signal that behavior changed, not as prose to quietly edit.
Keeping docs close to behavior
Keeping docs close to behavior means writing each explanation where the reader will look for it (module, class, function) and updating it in the same change that alters the behavior. Prose that describes an old version is worse than no prose, because a reader trusts it and acts on it. The practical test is the example and the exception list: if either no longer reproduces, the documentation has drifted.
Walkthrough
- The string on the first line of the body is the docstring; it is not assigned and not printed, which is exactly why
normalize_email.__doc__andhelp(normalize_email)can show it later. Move it below any other statement and it becomes an ordinary literal with no documentation effect. - The signature documents shape:
value: strand-> strsay a string goes in and a string comes out, but say nothing about whitespace or letter case, which the prose supplies. - The docstring states the transformation (
strip, thencasefold) and one boundary a reader would otherwise assume wrong: no deliverability validation. The body stays three words long because the prose describes the contract rather than repeating the steps. - Predict before running: what
normalize_email(" [email protected] ")returns, and which two string methods the result went through.
Experiments to try
- Print
normalize_email.__doc__and callhelp(normalize_email); then insertpassabove the string in the body and confirm that__doc__becomesNone. - Call
normalize_email(None)and record theAttributeError; note in one sentence why thestrannotation did not prevent the call. - Rewrite the docstring as a one-line summary, a blank line, and the details, then compare the
help()output with the original. - Add an example line such as
>>> normalize_email(" [email protected] ")to the docstring and verify it by running the same call in the REPL; then remove.strip()from the body and record how the example and the behavior diverge.
Common mistakes
- Writing docstrings that narrate the body ("first strips, then folds") instead of the contract ("returns the identifier without validating deliverability"): narration goes stale with every refactor and says nothing about what callers may expect.
- Treating type hints as complete documentation: hints describe shapes, not units, ranges, ordering, side effects, or raised exceptions, and nothing enforces them at runtime, so
normalize_email(None)still runs untilNone.strip()fails. - Leaving a docstring that no longer matches behavior after the code changed: false prose is worse than missing prose because readers trust it, and the drift stays invisible until someone runs the documented example.
- Writing a string literal that is not the first statement and expecting it to register as the docstring, or duplicating the same explanation in a comment block: only the first statement becomes
__doc__, and duplicated prose drifts out of sync.
Practice: Easy
- Run
print(normalize_email.__doc__)andhelp(normalize_email); then insert apassstatement above the docstring in the body and show that__doc__becomesNone. - Rewrite the docstring as one summary line, a blank line, and the details; compare the
help()output with the original and note which line becomes the summary. - Call
normalize_email(None)and record theAttributeError; write one sentence explaining why thestrhint did not stop the call.
Practice: Medium
- Write a module docstring for a small script that imports two functions, stating what the file is for and when to use it; compare what
help(module)shows before and after. - Write a docstring for a function that mutates its argument, such as
def add_tag(tags, tag), making the mutation explicit in prose because thelisthint cannot; add aRaisesnote for an input it refuses. - Add an example line to the
normalize_emaildocstring and verify it by running the same call in the REPL; then remove.strip()from the body, rerun, and record how the example and reality diverge.
Practice: Hard
- Document a small module completely (module, one class, two functions) with contracts, an example per function, and type hints; verify every example by pasting it into the REPL and list what the hints still leave unstated.
- Take a function whose docstring narrates its body step by step, rewrite it as a contract docstring (parameters, returns, raises, one boundary case), and confirm the new version stays true after you refactor the body while the old one would not.
- Run a drift audit: pick three docstrings from your own code, execute each documented example or boundary claim, record which still hold, and update the rest; state for each whether the fix was the prose or the code.
Lesson checklist
- I can identify the docstring in a module, class, function, or method and read it with
help(). - I can write a function docstring that states its contract without narrating the body.
- I can say what a type hint documents and what still needs prose.
- I can name one sign that documentation drifted from behavior and say where the fix belongs.
Remember
Documentation is the contract surface around code: the module docstring says what the file is for, class and function docstrings state expectations and exceptions, and type hints add value shapes that tools can check. Prose earns its place by saying what the code cannot (intent, units, boundaries), and it stays truthful only while someone keeps it in step with behavior.
Interview angles
What is the main purpose of **Docstrings**?+
A docstring is a string literal placed first in a module, class, function, or method body. Tools expose it through __doc__ and use it for generated documentation and interactive help.
What should you pay attention to when using **Module docs**?+
The module docstring is the first string literal in the file, and it tells a reader what the module is for and when to reach for it. Tools expose it through help(module) and __doc__, which makes it the entry point of generated documentation.
How does **Function docs** fit into this lesson?+
A function docstring records the contract a caller needs: what each parameter means, what is returned, which exceptions can be raised, and any non-obvious decision. It belongs immediately below the def line so help() can find it, and it should describe behavior rather than narrate the body line by line.
What does a type hint fail to document?+
Hints describe the shape of values, not their meaning: units, allowed ranges, ordering, side effects, and raised exceptions all stay unstated, and nothing enforces the hint at runtime, so a wrong-typed call still runs until an operation fails.