Python has 3 ways to create comments:
Single line comment:
# This is a single line comment in Python
Inline comment:
print(“Hello World”) # This is an inline comment
Multi-line comment:
"""
This type of comment spans multiple lines.
These are mostly used for documentation of functions, classes and modules.
"""
'''
Also a multi-line comment.
'''
A docstring is a multi-line comment used to document modules, classes, functions and methods. It has to be the first statement of the component it describes.
Developers should follow the PEP257 - Docstring Conventions guidelines. In some cases, style guides (such as Google Style Guide ones) or documentation rendering third-parties (such as Sphinx) may detail additional conventions for docstrings.
def hello(name):
"""Greet someone.
Print a greeting ("Hello") for the person with the given name.
"""
print("Hello "+name)
class Greeter:
"""An object used to greet people.
It contains multiple greeting functions for several languages
and times of the day.
"""
The value of the docstring can be accessed within the program and is - for example - used by the help
command.
PEP 257 defines a syntax standard for docstring comments. It basically allows two types:
According to PEP 257, they should be used with short and simple functions. Everything is placed in one line, e.g:
def hello():
"""Say hello to your friends."""
print("Hello my friends!")
The docstring shall end with a period, the verb should be in the imperative form.
Multi-line docstring should be used for longer, more complex functions, modules or classes.
def hello(name, language="en"):
"""Say hello to a person.
Arguments:
name: the name of the person
language: the language in which the person should be greeted
"""
print(greeting[language]+" "+name)