Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading