Concepts / Writing Effective Functions

Writing Effective Functions

A docstring is a documentation string stored as part of a Python function object. It remains accessible during program execution.

  • Programming

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.

Key point

A docstring is a documentation string stored as part of a Python function object. It remains accessible during program execution.

function object__doc__documentation stringrunning programstoresaccesses
Where does a docstring live in relation to its function, and how can a running program access it?

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.

python

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.

comment# explanationignoreddocstringdocumentation string__doc__stored documentationPython executesPython stores
What happens to a docstring versus a comment when Python executes the program?
FeatureDocstringComment
FormA string literal placed immediately after the function definition lineText preceded by the hash symbol
Treatment by PythonStored as part of the function objectIgnored completely
Runtime accessAvailable through __doc__ and help()Not stored or accessible to the running program
Tool supportCan support IDE tooltips and documentation generatorsDoes 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.

Worked example

Inspecting a Function's Docstring

Create a function with a docstring, then retrieve that documentation while the program is running.

  1. 1
    Define the function

    Place a triple-quoted string immediately after the function definition line. This makes the string the function's docstring.

  2. 2
    Access __doc__

    Read the function's special __doc__ attribute to retrieve the stored documentation string.

  3. 3
    Use help()

    Pass the function to help() to display documentation based on its docstring.

Result

The same function documentation can be accessed directly through __doc__ or displayed through help().

Code walkthrough
def calculate_total(price, quantity):
    """Return the total price for a given quantity."""
    return price * quantity

print(calculate_total.__doc__)
help(calculate_total)
  1. 1
    Python creates the calculate_total function object and stores its documentation string with it.
  2. 2
    The print statement reads calculate_total.__doc__ and displays the stored text.
  3. 3
    The 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.
Output
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.

In the real world

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 like
    def greet_user(name):
        # Return a greeting for a user.
    Why it fails

    Python ignores comments completely. The text is not stored with the function and cannot be retrieved through __doc__ or displayed by help().

    Do this instead

    Use 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 like
    def greet_user(name):
        greeting = "Hello"
        """Return a greeting for a user."""
    Why it fails

    A docstring is defined by its placement immediately after the function definition line.

    Do this instead

    Put the documentation string before the function's other statements.

  • Common mistake

    Forgetting that runtime access is available

    What it looks like

    Only reading the function source code and never checking its stored documentation

    Why it fails

    The function's docstring can be retrieved during execution through the __doc__ attribute or displayed with help().

    Do this instead

    Use 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?

  • The explanation from the comment

  • The function name

  • The comment is not stored as the function's docstring

  • The function's return value

Reveal answer
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

EASY

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__.
  1. 1
    Place a clear string literal immediately after the function definition line.
  2. 2
    Use triple quotes when the documentation needs multiple lines.
  3. 3
    Remember that comments are ignored and are not available at runtime.
  4. 4
    Retrieve documentation with the function's __doc__ attribute or display it with help().
  5. 5
    Write docstrings that clarify the function's purpose and help explain what its parameters expect.

Key Takeaways

  1. 1
    A docstring is a documentation string stored as part of a Python function object.
  2. 2
    A docstring must be placed immediately after the function definition line.
  3. 3
    Comments begin with a hash symbol and are ignored completely by Python, while docstrings remain accessible.
  4. 4
    A function's docstring can be retrieved with __doc__ or displayed with help().
  5. 5
    Docstrings 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__ or help() to access a function's documentation at runtime.
  • Clear docstrings help readers, future maintainers, IDEs, and documentation generators.

Related concepts

More concepts starting with W