FUN with Python
In this section, we will describe our best practices when dealing with Python code.
PEP 8
Your code should at least follow the PEP 8 style guide with one single exception: the maximal line length is 99 characters (instead of the default 79 characters).
Usually, we enforce this convention by adding a linting step to our continuous integration workflow using flake8
with the following settings in the project's setup.cfg
:
Documentation
The minimal documentation your code should have is a docstring (see PEP 257) per module, method, class and function. For now we do not force you to use a particular style or describe all method or function arguments; we want you to explain to your peers (and maybe you in a few months) what your code is trying to achieve. Remember that it should be written for humans, while your code is for machines (and humans 🤓).
This also applies for tests, e.g.:
Indentation
We had long discussions about following the PEP 8 (with maximal line length) and having an indentation style that satisfies everyone. Our consensus follows:
Until you hit the 99 characters limit, write your statement in one line:
If your statement is too long, then split your line with one argument per line:
Pro tip: To fit with the maximal line length limit for long strings, think parentheses!
Import
Import statements should respect the following requirements:
write global import statements first (
import logging
) then partial imports (from copy import copy
),import statements should be written in the following order: 1. standard library, 2. Django imports 3. third party dependencies, and 4. application modules (relative imports); with an empty row between each,
import statements should be sorted alphabetically (
import bar
is written beforeimport foo
),imported objects from a module should also be sorted alphabetically (
from foo import bar, baz, lol
).
An example follows:
Test files
In Django, we want good names for our test files: they should bear the name of the Python module being tested (followed by the snakecased name of the class or method if necessary), from the more generic to the more specific.
Some examples of good names for test files:
Last updated