Eoin Dowling
Eoin Dowling

Reputation: 433

Should a docstring go before or after a decorator?

Compare the following.

Example 1: docstring before decorator.

@app.route("/")
"""
summary
"""
def hello() -> str:
    return "Hello World"

versus example 2: docstring after decorator:

"""
summary
"""
@app.route("/")
def hello() -> str:
    return "Hello World"

Upvotes: 2

Views: 1330

Answers (2)

BrokenBenchmark
BrokenBenchmark

Reputation: 19243

Neither, they should go under the function header, like so:

@app.route("/")
def hello() -> str:
    """
    summary
    """
    return "Hello World"

PEP 257 discusses the convention for docstrings in more detail. It states that these docstrings are set to the __doc__ attribute of a given function or class (as described in the PEP linked above).

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object.

These docstrings appear when help() is invoked, like as follows:

>>> @app.route("/")
... def hello() -> str:
...     """
...     summary
...     """
...     return "Hello World"
...
>>> help(hello)
Help on function hello in module __main__:

hello() -> str
    summary

The other placements you've described do not set the __doc__ attribute, and thus do not have the same behavior with help().

Upvotes: 5

brandizzi
brandizzi

Reputation: 27050

Where should the docstring go?

The docstring should go inside the function, the first thing after the function header:

@app.route("/")
def hello() -> str:
    """
    summary
    """
    return "Hello World"

The specification itself (PEP 257) makes it explicit:

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition.

Why?

It is important because docstrings are not just a convention.

If you put them in the right place, you can see the function documentation with the help() function (and maybe even other tools):

>>> @app.route("/")
... def hello() -> str:
...     """
...     summary
...     """
...     return "Hello World"
... 
>>> help(hello)
Help on function hello in module __main__:

hello() -> str
    summary

This happens because, if a string literal is the first thing in the function declaration, the interpreter will set it to the __doc__ attribute of the function:

>>> hello.__doc__
'\n    summary\n    '

help() basically just displays, nicely formatted, the value of the __doc__ attribute.

Upvotes: 9

Related Questions