Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Function docstrings, `__doc__`, and `__name__`

Read a function's documentation without calling it, and preserve its name and docstring across decoration so audit logs and reports describe the intended function.

Version: Python 3.12

Syntax

def f():
    """Describe what the function does."""
    ...

f.__doc__
f.__name__
f.__doc__ = "Updated documentation."

In Python 3.12, a function docstring is a string literal that stands as the first statement of the function body. Blank lines and comments are not statements, so they can come before it. A # comment, a later string literal, or an f-string (even without substitutions) does not set __doc__. Triple double quotes are a PEP 257 convention, not a syntax requirement.

f.__doc__ reads the documentation stored on the function object without calling f. Missing documentation is None, not the empty string ''. This attribute is writable on user-defined functions. Use f.__doc__ to report the stored value as-is, or inspect.getdoc(f) to display documentation with cleaned-up indentation. CPython's -OO option discards docstrings, so don't make program behavior depend on them.

f.__name__ is separate: it holds the function's name, not its documentation. Assigning alias = f creates another reference to the same object without renaming it. If a decorator returns a new wrapper function without copying metadata, an audit sees the wrapper's name and documentation. Apply @functools.wraps(f) to the wrapper definition: by default it copies __name__ and __doc__ among other attributes and sets __wrapped__ to the wrapped function.

Examples

from functools import wraps


def audit(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Audit: {wrapper.__name__}")
        return func(*args, **kwargs)

    return wrapper


@audit
def compute_net(gross, fee):
    """Return gross minus fee."""
    return gross - fee


print(f"Documentation: {compute_net.__doc__!r}")
print(f"Net: {compute_net(120, fee=15)}")

Result

Documentation: 'Return gross minus fee.'
Audit: compute_net
Net: 105

The report first reads the docstring without calling `compute_net`. The wrapper then logs the preserved name and forwards the arguments; the calculation returns `105`.

Related lessons

  • Python · Lesson 10 · Advanced · Version: 5

Sources