Formatting#

Following the PEP8 style guide#

To ensure that your Python-code is well formatted, one can use tools such as flake8, which can be installed with

python -m pip install flake8

Flake8 checks the consistency (following the PEP8 style guide) of your code, using

  • Pyflake, with the following checks

  • Pycodestyle, with the following checks

Flake8 can be executed with

python -m flake8

Call

python -m flake8 --help

for listing the listing options

We add a .flake8 file in the project root with some additional configurations

[flake8]
exclude = docs,venv
max-line-length = 100

To ignore flake8 formatting on certain lines, or ignore certain rules, see: Ignoring Errors with Flake8.

Code consistency#

Flake8 only checks the consistency of your code to a certain extent. Modern Python allows for type hints which means that you can specify the input and output type for functions.

However, type-checking does not happen during run-time. We prefer using mypy to perform these checks. Mypy can be installed from The Python Package Index (PYPI)

python -m pip install mypy

and be executed as

python -m mypy

We add the following options to pyproject.toml

[tool.mypy]
ignore_missing_imports = true
# Folders to exclude
exclude = [
    "docs/",
    "build/"
]
 # Folder to check with mypy
files = [
    "src",
    "tests" # Does not show errors when importing untyped libraries
]

where ignore_missing_imports is set to True to suppress all errors coming from third-party libraries that are untyped.

To let mypy ignore single lines or whole files, see: Locally silencing the checker.