Writing Effective Functions
A docstring is a documentation string stored as part of a Python function object. It remains accessible during program execution.
The Function's Built-In Explanation
A function can perform the correct task and still be difficult to use if nobody knows what it does. A docstring gives the function an explanation that Python keeps with the function itself. That makes the explanation useful not only to a reader looking at the source code, but also to a running program and to tools that display or generate documentation.
A docstring is a documentation string stored as part of a Python function object. It remains accessible during program execution.
Placing the Documentation
A docstring is a string literal placed immediately after the function definition line. Python can use single quotes, double quotes, or triple quotes for this string. Triple quotes are preferred when the documentation spans multiple lines because they allow multiple lines without requiring escaped newlines.
Docstrings and Comments
Docstrings and comments both help document code, but Python treats them differently. A comment is text preceded by the hash symbol. Python ignores a comment completely: it is not stored and cannot be accessed by the running program. A docstring is a string literal associated with the function object, so the program can retrieve and display it.
| Feature | Docstring | Comment |
|---|---|---|
| Form | A string literal placed immediately after the function definition line | Text preceded by the hash symbol |
| Treatment by Python | Stored as part of the function object | Ignored completely |
| Runtime access | Available through __doc__ and help() | Not stored or accessible to the running program |
| Tool support | Can support IDE tooltips and documentation generators | Does not provide this function documentation mechanism |
Docstrings and comments document code differently because Python handles them differently.
Reading Documentation at Runtime
Because Python stores a function's docstring, a program can retrieve it while running. The special __doc__ attribute contains the function's documentation string. The help() function also uses docstrings to display documentation.
Inspecting a Function's Docstring
Create a function with a docstring, then retrieve that documentation while the program is running.
- 1Define the function
Place a triple-quoted string immediately after the function definition line. This makes the string the function's docstring.
- 2Access __doc__
Read the function's special
__doc__attribute to retrieve the stored documentation string. - 3Use help()
Pass the function to
help()to display documentation based on its docstring.
The same function documentation can be accessed directly through __doc__ or displayed through help().
def calculate_total(price, quantity):
"""Return the total price for a given quantity."""
return price * quantity
print(calculate_total.__doc__)
help(calculate_total)- 1Python creates the
calculate_totalfunction object and stores its documentation string with it. - 2The print statement reads
calculate_total.__doc__and displays the stored text. - 3The
help()call displays information that includes the function's docstring.
- The function definition gives the function a name and parameters.
- The triple-quoted string immediately after the definition is the docstring.
- The
__doc__attribute retrieves the stored documentation string. help()displays documentation using the function's docstring.
Return the total price for a given quantity.
Help on function calculate_total in the current context:
calculate_total(price, quantity)
Return the total price for a given quantity.Why Documentation Pays Off
A well-written docstring improves code clarity by helping readers understand what a function does. It also helps your future self remember what the function does and what its parameters expect. Because docstrings remain available to tools, they can also provide IDE tooltips and supply material for documentation generators that build reference manuals.
A developer can hover over a function name in an integrated development environment and see its docstring as a tooltip. A documentation generator can also extract the same stored text to help build a reference manual.
Mistakes Beginners Make
Common mistake Writing a comment and expecting it to become function documentation
What it looks likedef greet_user(name): # Return a greeting for a user.Why it failsPython ignores comments completely. The text is not stored with the function and cannot be retrieved through
__doc__or displayed byhelp().Do this insteadUse a string literal immediately after the function definition line when the text is intended to be the function's docstring.
Common mistake Placing the string somewhere other than immediately after the function definition line
What it looks likedef greet_user(name): greeting = "Hello" """Return a greeting for a user."""Why it failsA docstring is defined by its placement immediately after the function definition line.
Do this insteadPut the documentation string before the function's other statements.
Common mistake Forgetting that runtime access is available
What it looks likeOnly reading the function source code and never checking its stored documentation
Why it failsThe function's docstring can be retrieved during execution through the
__doc__attribute or displayed withhelp().Do this insteadUse function_name.__doc__ for direct access or help(function_name) for displayed documentation.
What do you think happens?
If a function has a hash-prefixed explanation instead of a string literal immediately after its definition, what will its __doc__ attribute contain?
Reveal answer
The comment is not stored as the function's docstring.
Python ignores comments completely. A function docstring must be a string literal placed immediately after the function definition line.
Practice and Recall
Imagine a function named format_title. Write a one-line docstring that explains what the function does. Then identify which expression would retrieve its documentation during execution: format_title.__doc__ or format_title.comment.
Hints
- The docstring must be a string literal immediately after the function definition line.
- The special runtime attribute is named
__doc__.
- 1Place a clear string literal immediately after the function definition line.
- 2Use triple quotes when the documentation needs multiple lines.
- 3Remember that comments are ignored and are not available at runtime.
- 4Retrieve documentation with the function's
__doc__attribute or display it withhelp(). - 5Write docstrings that clarify the function's purpose and help explain what its parameters expect.
Key Takeaways
- 1A docstring is a documentation string stored as part of a Python function object.
- 2A docstring must be placed immediately after the function definition line.
- 3Comments begin with a hash symbol and are ignored completely by Python, while docstrings remain accessible.
- 4A function's docstring can be retrieved with
__doc__or displayed withhelp(). - 5Docstrings improve clarity and support IDE tooltips and documentation generators.
At a glance
- Docstrings give functions documentation that Python stores and preserves during program execution.
- The defining placement is immediately after the function definition line.
- Comments and docstrings are not interchangeable: comments are ignored, while docstrings become part of the function object.
- Use
__doc__orhelp()to access a function's documentation at runtime. - Clear docstrings help readers, future maintainers, IDEs, and documentation generators.