Search code examples
pythondecoratorpep8docstring

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"

Solution

  • 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.