Python DocStrings, Annotations and PEP8
Python Docstring is the documentation string which is string literal, and it occurs in the class, module, function or method definition, and it is written as a first statement. Docstrings are accessible from the doc attribute for any of the Python object and also with the built-in help() function can come in handy.
One-line Docstrings
The one-line Docstrings are the Docstrings which fits all in one line. You can use one of the quotes, i.e., triple single or triple double quotes and opening quotes and closing quotes need to be the same. In the one-line Docstrings, closing quotes are in the same line as with the opening quotes. Also, the standard convention is to use the triple-double quotes.
def square(a):
'''Returns argument a is squared.'''
return a**a
>>> print(square.__doc__)
Returns argument a is squared.
>>> help(square)
Help on function square in module __main__:
square(a)
Returns argument a is squared.
(END)
Multi-line Docstrings
Multi-line Docstrings also contains the same string literals line as in One-line Docstrings, but it is followed by a single blank along with the descriptive text.
The general format for writing a Multi-line Docstring is as follows:
def some_function(argument1):
"""Summary or Description of the Function
Parameters:
argument1 (int): Description of arg1
Returns:
int:Returning value
"""
return argument1
Popular Docstring Formats
There are many Docstrings format available, but it is always better to use the formats which are easily recognized by the Docstring parser and also to fellow Data Scientist/programmers. There is no any rules and regulations for selecting a Docstring format, but the consistency of choosing the same format over the project is necessary. Also, It is preferred for you to use the formatting type which is mostly supported by Sphinx. The most common formats used are listed below.
Formatting Type | Description |
---|---|
NumPy/SciPy | Combination of reStructured and GoogleDocstrings and supported by Sphinx |
PyDoc | Standard documentation module for Python and supported by Sphinx |
EpyDoc | Render Epytext as series of HTML documents and a tool for generating API documentation for Python modules based on their Docstrings |
Google Docstrings | Google's Style |
Google Style
Google Style is easier and more intuitive to use. It can be used for the shorter form of documentation.
class Vehicles(object):
'''
The Vehicle object contains a lot of vehicles
Args:
arg (str): The arg is used for...
*args: The variable arguments are used for...
**kwargs: The keyword arguments are used for...
Attributes:
arg (str): This is where we store arg,
'''
def __init__(self, arg, *args, **kwargs):
self.arg = arg
def cars(self, distance,destination):
'''We can't travel distance in vehicles without fuels, so here is the fuels
Args:
distance (int): The amount of distance traveled
destination (bool): Should the fuels refilled to cover the distance?
Raises:
RuntimeError: Out of fuel
Returns:
cars: A car mileage
'''
pass
The Google Style is better than Sphinx style. It also has an inconvenient feature, i.e. In the above code, the multi-line description of the distance would look messy. That is why the Numpy can be used for the more extended form of documentation.
Numpy Style
Numpy style has a lot of details in the documentation. It is more verbose than other documentation, but it is an excellent choice if you want to do detailed documentation, i.e., extensive documentation of all the functions and parameters.
class Vehicles(object):
'''
The Vehicles object contains lots of vehicles
Parameters
----------
arg : str
The arg is used for ...
*args
The variable arguments are used for ...
**kwargs
The keyword arguments are used for ...
Attributes
----------
arg : str
This is where we store arg,
'''
def __init__(self, arg, *args, **kwargs):
self.arg = arg
def cars(self, distance, destination):
'''We can't travel distance in vehicles without fuels, so here is the fuels
Parameters
----------
distance : int
The amount of distance traveled
destination : bool
Should the fuels refilled to cover the distance?
Raises
------
RuntimeError
Out of fuel
Returns
-------
cars
A car mileage
'''
pass
The above example is more verbose than any other documentation. It is more lengthy and could only be used for the long and detailed documentation.
Python Built-in Docstrings
You can also view the built-in Python Docstrings.
The all the built-in function, classes, methods have the actual human description attached to it. You can access it in one of two ways.
- doc attribute
- The help function
For Example:
import time
print(time.__doc__)
Similarly, the help can be used by:
help(print)
Help on built-in function print in module builtins:
print(...)
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.
Python PEP8
PEP 8, sometimes spelled PEP8 or PEP-8, is a document that provides guidelines and best practices on how to write Python code. It was written in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan. The primary focus of PEP 8 is to improve the readability and consistency of Python code. You can learn about these by reading the full PEP 8 documentation
Naming Styles
The table below outlines some of the common naming styles in Python code and when you should use them:
Type | Naming Convention | Examples |
---|---|---|
Functions | Use a lowercase word or words. Separate words by underscores to improve readability. | function, my_function |
Variable | Use a lowercase single letter, word, or words. Separate words with underscores to improve readability. | x, var, my_variable |
Class | Start each word with a capital letter. Do not separate words with underscores. This style is called camel case. | Model, MyClass |
Method | Use a lowercase word or words. Separate words with underscores to improve readability. | class_method, method |
Constant | Use an uppercase single letter, word, or words. Separate words with underscores to improve readability. | CONSTANT, MY_CONSTANT, MY_LONG_CONSTANT |
Module | Use a short, lowercase word or words. Separate words with underscores to improve readability. | module.py, my_module.py |
Package | Use a short, lowercase word or words. Do not separate words with underscores. | package, mypackage |
Recommendations
-
Avoid trailing whitespace anywhere. Because it's usually invisible, it can be confusing: e.g. a backslash followed by a space and a newline does not count as a line continuation marker. Some editors don't preserve it and many projects (like CPython itself) have pre-commit hooks that reject it.
-
Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).
-
If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies). Use your own judgment; however, never use more than one space, and always have the same amount of whitespace on both sides of a binary operator.
Yes
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)
No
i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
- Don't use spaces around the = sign when used to indicate a keyword argument, or when used to indicate a default value for an unannotated function parameter.
Yes:
def complex(real, imag=0.0):
return magic(r=real, i=imag)
No:
def complex(real, imag = 0.0):
return magic(r = real, i = imag)
When combining an argument annotation with a default value, however, do use spaces around the = sign:
Yes:
def munge(sep: AnyStr = None): ...
def munge(input: AnyStr, sep: AnyStr = None, limit=1000): ...
No:
def munge(input: AnyStr=None): ...
def munge(input: AnyStr, limit = 1000): ...
Sources
- https://www.datacamp.com/community/tutorials/docstrings-python