Python docstrings
Python docstrings
Python docstrings are the string literals that appear immediately after the definition of a function, method, class, or module.
For example:
def sum(a, b):
'''Takes in two numbers, returns their sum'''
return a+b
where the string literal of the sum()
function is
'''Takes in a number n, returns the square of n'''
You can use either triple '''
or """
quotation marks to create docstrings.
Python Comments vs Docstrings
Python Comments
Comments are essential when writing a program because they describe what happens inside a program.
They are completely ignored by the Python interpreter.
In Python, the symbol #
is used to write a single-line comment.
For example:
# print Hello World
print("Hello World")
Python Comments Using Strings
If you do not assign strings to any variables, they serve as comments.
"This is a single-line comment"
'''
This is a
multi-line
comment
'''
print("Hello World")
Triple quotation marks is used for multi-line strings.
Python docstrings
Python docstrings are strings used immediately after the definition of a function, method, class, or module to document the code.
Python docstrings can be accessed using the __doc__
attribute.
Python __doc__
attribute
Whenever string literals are present immediately after the definition of a function, module, class, or method, they are associated with the object as the __doc__
attribute.
In this way, string literals can be retrieved using the __doc__
attribute.
For example, the documentation of our sum()
function can be accessed using the __doc__
attribute:
def sum(a, b):
'''Takes in two numbers, returns their sum'''
return a+b
print(sum.__doc__)
Output
Takes in two numbers, returns their sum
The __doc__
attribute can be used to access the documentation of built-in functions.
For example, the documentation of the print()
function:
print(print.__doc__)
Output
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Single-line docstrings in Python
Single-line docstrings are those that fit in one line.
The following are some standard guidelines for writing single-line docstrings:
- Even though they are single-line, we still use triple quotes around these strings because they can be expanded easily later.
- Closing quotation marks are on the same line as opening quotation marks.
- There are no blank lines either before or after the docstring.
- They must be concise and indicate what is in input and what is in output.
An example of single-line docstrings for a function:
def sum(a, b):
'''Takes in two numbers, returns their sum'''
return a+b
Multi-line Docstrings in Python
Multi-line docstrings consist of a summary line, just like a one-line docstring, followed by a blank line and a more detailed description.
The PEP 257 document provides standard conventions for writing multiline documents for various objects.
The most important and frequent are illustrated below.
1. Docstrings for Python Modules
Docstrings for Python Modules should list all available classes, functions, objects, and exceptions that are imported when the module is imported.
They should also have a one-line summary for each item.
Docstrings for Python Modules are written at the beginning of the Python file.
For example, we want print the docstring of foo
module:
import foo
print(foo.__doc__)
Output:
A test module for Tutorial Reference
Classes:
FooClass
BarClass
Functions:
do_something(object)
do_something_else(object) -> string
read_something(file) -> object
load_something(string) -> object
Misc variables:
__version__
count_number
available_formats
2. Docstrings for Python Functions
The docstring of a function or method must summarize its behavior and document its arguments and return values.
It should also list all exceptions that can be raised and other optional arguments.
For example:
def sum(a, b):
'''
Returns the sum of two decimal numbers.
Parameters:
a (int): A decimal integer
b (int): Another decimal integer
Returns:
a+b (int): sum of a and b
'''
return a+b
print(sum.__doc__)
3. Docstrings for Python Classes
The docstrings for classes should summarize their behavior and list public methods and instance variables.
Subclasses, constructors, and methods must each have their own docstrings.
For example, define a Person class:
class Person:
"""
A class to represent a person.
Attributes
name : str
first name of the person
surname : str
family name of the person
age : int
age of the person
Methods
info(additional=""):
Prints the person's name and age.
"""
def __init__(self, name, surname, age):
"""
Constructs a person with name, surname and age
Parameters:
name : str
first name of the person
surname : str
family name of the person
age : int
age of the person
"""
self.name = name
self.surname = surname
self.age = age
def info(self, additional=""):
"""
Prints the name and age of the person.
If the argument 'additional' is passed, then it is appended after the main info.
Parameters:
additional : str, optional
More info to be displayed (default is None)
Returns:
None
"""
print(f'My name is {self.name}{self.surname}. I am {self.age} years old.' + additional)
You can also use the help()
function to read the documentation associated with various objects and the methods associated with that class.
For example, you can use the help()
function on the class Person
in this way: help(Person)
4. Docstrings for Python Scripts
The docstrings for Python script should document the script functions and command line syntax as a usable message.
It should serve as a quick reference to all functions and arguments.
5. Docstrings for Python Packages
The docstrings for a Python package is written in the package's __init__.py
file.
- It should contain all available modules and subpackages exported from the package.
For example, consider a package named greetings with a module hello_world. Your package structure looks like this:
greetings/
│
├── __init__.py
└── hello_world.py
In the __init__.py
, you can write a simple docstring:
"""
greetings - A package for generating greetings.
Modules:
- hello_world: Prints a greeting message.
"""
from.hello_world import greet