Skip to content

Python Style Guide

Python developers defined a set of recommendations and good practices for writing code to be readable and consistent. Documents containing the Python Style Guide are:

  • PEP 8 - about the source code
  • PEP 257 - about documenting code (called docstrings)

Code is read more often than written, and additionally it is usually read not by the author, so it is important to stick to generally accepted rules.

Naming conventions

Each non-trivial program contains many names of various entities: variables, functions, classes, etc. The code should document as well as possible, so it is important to use meaningful names (more in Clean Code). Additionally, the following conventions are recommended to be followed:

  • functions - we use snake case (individual words consist of lowercase letters and are connected with each other by an underscore) - e.g. execute, open_window
  • variables - "snake case" - e.g. x, current_user
  • classes - "camel case" (individual words start with capital letters and are written in one string without any connecting characters) - e.g. Handler, MainWindow
  • class methods - "snake case" - e.g. undo, parse_answer
  • constants - "SNAKE CASE" (but this time only capital letters) - e.g. TAU, MAX_VALUE
  • modules - "snake case" - e.g. parser.py, gsm_modem.py
  • packages - lowercase letters without separators - e.g. lte, supersort

Code layout

It is recommended that the Python code have a lot of space for better reading comfort - detailed rules:

  • each global function and class should be surrounded by two blank lines
  • all class methods should be surrounded by single empty lines (except the first)
  • blank lines should separate logical steps of the algorithm
  • there should be no more than 79 characters in the line, so that everything fits on the screen
  • you should avoid \ to break lines into shorter ones

Indents

Code blocks in Python are indented, so you shouldn't be too flexible in formatting your code, but there are a few rules to stick to:

  • spaces are preferred over tabs
  • one indent level equals 4 spaces
  • when dividing a long line, additional indents are recommended to increase readability

Comments

Basically the code should be * self-documenting * but in practice comments cannot be avoided. Useful Notes:

  • to describe one operation we use inline comments at the end of the line (starting with the # character)
  • we explain larger pieces of code with block comments
  • functions, classes, methods, modules should be described using the so-called docstrings (PEP 257 - more info below)

Spaces in expressions and statements

In addition to the space added by blank lines, it is also recommended to padding code spaces around the operators:

  • assignments (=, +=, ...): a = 10
  • comparisons (==, <, is, not in, ...): if value == 10:
  • logical (and, not, ...): if value > 10 and value < 20:

Programming

Several seemingly insignificant principles regarding programming can be found in the document PEP 8

  • we do not compare the values of boolean variables to True and False: if valid: and not if valid == True:
  • we use a logical context (e.g. an empty list is False): if work_list: not if len (work_list)> 0:
  • we use is not instead of not ... is in if statement: if x is not None: not if not x is None
  • we don't use if x:if we mean if x is not None
  • we use .startswith () and .endswith () instead of slicing

liners

Python's coding style rules are clearly defined enough to be automatically checked. The most popular programs (called liners) that analyze code and pinpoint stylistic problems are:

  • pycodestyle
  • flake8 - additionally containing debugger functions
  • pylint - looking for programming errors, problematic code, suggesting fixes

Often, this type of software is available as an editor plug-in or IDE.

Autoformaters

Following the trail of automatic code control, we find autoformaters. They add to the functionality of liners automatic code corrections. The most popular autoformaters:

  • autopep8 - using pycodestyle
  • yapf - made by Google
  • black
    • advertised by the creators as "uncompromising code formatter"
    • apply the formatting rules of PEP 8 + add-ons
    • has limited configuration options, which translates into an exceptionally consistent style of formatting and allows you to focus on the content of the code, not on its formatting options

PEP 257 - docstring

The so-called docstrings are used to comment on larger pieces of code. Detailed rules for their use are described in the document PEP 257. At the beginning of your adventure with documentation, it is worth sticking to the basic rules:

  • use them to document all public modules, functions, classes, and methods
  • start and end your docstring with triple quotes
  • surround a single-line docstring with triple quotes on the same line
  • end a multi-line docstring with triple quotes on a new line

Usage example showing recommended content:

def my_function(name):
    """Designation of function.

    Parameter description (optional)

    Return values (optional)

    Prerequisites (optional)

    Side effects (optional)

    Additional information (further explanation, bibliography references, usage examples) (optional)
    """
    pass