Docstring
A docstring is a string written as the first statement of a module, function, class, or method. Triple quotation marks allow it to span lines. Python stores it on the object as __doc__, so help(seed_needed), inspect.getdoc(), and editor tooltips can show it, and documentation generators can collect it.
That storage is what separates a docstring from a comment. A comment beginning with # exists only in the source file and is not attached to the object as __doc__; tools can still read it from source. A docstring is part of the object, which is why it belongs in the contract of a function rather than in its internal notes.
A useful docstring states what the function returns, what each input means including its unit, and the conditions under which it is valid: assumptions, rejected inputs, and errors it may raise. Start with one summary line that reads as a statement of the result, so a reader scanning help() output learns the point immediately. Describing behavior that the code does not have makes the docstring worse than none, so update it when the function changes.
Comments still have a job. Write them for reasoning that the code cannot show: why a threshold is 1000, why a row is rejected rather than fixed, where a rule came from. Step-by-step comments written while planning an algorithm are useful scaffolding, but once the code exists they usually restate it; what survives is the explanation of a choice. PEP 257 records the docstring conventions, and pydoc and IDEs assume them.
References: PEP 257: Docstring conventions, Documentation strings. See it in use in Python Functions, Modules, and Classes.
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
