Code Style Guidelines & Static Analysis Tools#

  • Code style guidelines help to make code readable, consistent, and maintainable

  • In Python, the most widely accepted standard is PEP8

  • Static analysis tools help to adhere to a style guide and discover likely bugs

PEP8 – Python Style Guide#

PEP8 defines conventions for:

  • Indentation (4 spaces)

  • Line length (max 79 characters)

  • Naming: snake_case for variables, CamelCase for classes

  • Spacing: around operators and after commas

  • Imports: standard library first, then third-party, then local

Bad Example:

def myFunction(x,y):

  return(x+y)

Good Example (PEP8):

def my_function(x, y):
    return x + y

Static Analysis - Liters, Formatters & Type Checker#

  • Formatters: Tools that reformat your code for stylistic consistency.

  • Linters: Tools that detect not just stylistic inconsistency but also potential bugs.

  • Type Checkers: Tools that ensure code is used as intended provided type hints are given.

We will use Ruff as a Python linter and code formatter.

Ruff can be integrated into PyCharm.

Ruff supports over 800 lint rules. The default rule set is fine: “it catches a wide variety of common errors (like unused imports) with zero configuration.” (astral.sh) More rules can be enabled in the pyproject.toml file.

For type checking we will rely on PyCharm built-in type checking capabilities.

Continuos integration & Pre-commit hooks#

There are two common tools to “enforce” consistent style in a project.

  1. Continuos Integration (CI):

  • Runs static analysis tools on the remote Git repository on the GitLab server.

  • It is triggered by a change in the Git repository

  1. Pre-commit hook

  • Runs static analysis tools on the local Git repository before a commit can be made.

  • It is triggert by a git commit