This is a style guide for writing code in Python 3.
As a base guide, the Flake8 Style Guide should be followed.
Note: Flake8 is a wrapper around the following linting tools:
When splitting statements over multiple lines, line breaks should occur before binary operators
Example:
first_number
+ second_number
- third_number
Example:
first_boolean
and second_boolean
and (
third_boolean
or not fourth_boolean
)
When the conditional of an if-statement needs to be split over multiple lines, it should adhere to the following format:
if (
this_is_one_thing
and this_is_another_thing
):
do_stuff()
do_some_other_stuff()
PEP 8 specifies three different import groups each separated by a blank line:
- Standard library imports.
- Related third party imports.
- Local application/library specific imports.
Within each of these groups, imports should be sorted alphabetically.
Example:
import os
import sys
from requests import Session
import yaml
import local_module
from second_local_module import first_thing, second_thing, third_thing
import z_another_local_module
Python Docstrings may be used to add documentation to Python code. The reStructuredText (reST) Docstring Format is the preferred docstring format.
- Visual Studio Code: autoDocstring plugin.
Add
"autoDocstring.docstringFormat": "sphinx"
to yoursettings.json
- Vim: vim-pydocstring plugin. Uses reST by default.
- Command Line: pyment. Uses reST output docstring format by default.
def sum(a, b):
"""Computes the sum of two numbers
:param a: The first number
:param b: The second number
:returns: The sum of a and b
"""
return a + b
from types import number
def sum(a: number, b: number) -> number:
"""Computes the sum of two numbers
:param number a: The first number
:param number b: The second number
:returns: The sum of a and b
:rtype: number
"""
return a + b
Note: Parameter types can also be placed on separate lines:
:param a: The first number
:type a: number
but return types must be on a separate line using :rtype
Strings should be single-quoted when possible. When single quotation marks are required in a string, the string should be double-quoted and the single quotation marks should be unescaped. When accessing a dictionary within an f-string, the string should be double-quoted and the dictionary keys should be single-quoted.
"A string with 'quoted examples'"
f"{obj['prop_a']['prop_b']} and {obj_2['prop_c']} are values"