[style, code, python, best practices, guidelines]


Overview

We follow Python’s style guide PEP 8, emphasizing readability and consistency. In this topic, we highlight some of the best practices with code examples.

Note that sometimes your own judgment is required, and what suits best for your project does not always comply with the guidelines!

Straightforward code

Keep the code as explicit and readable as possible. Both examples below return the same thing, while in the good example, it is more obvious what is happening.


# Good
def make_complex(x, y):
    return {'x': x, 'y': y}

# Bad
def make_complex(*args):
    x, y = args
    return dict(**locals())

Naming conventions

Use concise and meaningful names for variables, functions, classes, and modules. Avoid using dots (.) in names to prevent confusion with Python attributes and methods.

  • Function: function, my_function
  • Variable: x, var, var2, my_variable
  • Class: Model, MClass
  • Method: class_method, method
  • Constant: CONSTANT, MY_CONSTANT
  • Module: module.py, my_module.py
  • Package: package, mypackage
# Good
school_type = "Primary" # variable
class SchoolType:       # class
    pass

# Bad
school.type = 3     # variable 
class school_type:  # class
  pass

Maximum line length and line breaking

PEP 8 suggests lines should be limited to 79 characters. Python will assume line continuation if code is contained within parentheses, brackets, or braces:


# Good
def long_function_name(
      var_one, var_two, var_three,
      var_four, var_five, var_six):
    print(var_one)

# Bad
def long_function_name(var_one, var_two, var_three,var_four, var_five, var_six):
    print(var_one)

It is good practice to put the operators on the beginning of a new line, rather than breaking the line after the operator.

# Good
sum = (var1 
      + var2
      - var3)

# Bad
sum = (var1 + 
       var2 -
       var3)

Indentation and continuation lines

  • Use 4 spaces per indentation level
  • Align wrapped elements vertically within parentheses, brackets, and braces.
  • Avoid arguments on the first line without vertical alignment
# Good
fun = long_function_name(
    var_one, var_two
    var_three, var_four)

# Bad
foo = long_function_name(var_one, var_two,
    var_three, var_four)
  • Closing symbols may align with the first non-whitespace character of the last line or the first character of the line starting the construct.

# Both options work.
my_list = [
    1, 2, 3,
    4, 5, 6
    ]

my_list = [
    1, 2, 3,
    4, 5, 6
]

Imports

  • Place imports on separate lines for clarity and readability.
  • Organize imports in the following groups with blank lines between them: standard library imports, related third-party imports, local application/library-specific imports.
  • Always place imports at the top of the file before other code.
# Good
import os
import sys

# Bad
import sys, os

Whitespace

Avoid extraneous whitespace

  • Immediately inside parentheses, brackets, or braces
# Good
buy(item_list[0], {inventory: 2})

# Bad
buy( item_list[ 0 ], { inventory: 2 } )
  • Before a comma, semicolon, or colon
# Good
if x == 2: print(x, y); x, y = y, x

# Bad
if x == 2 : print(x , y) ; x , y = y , x
  • Before the open parenthesis that starts the argument list of a function call
# Good
buy(1)

# Bad
buy (1)
  • Between a trailing comma and a closing parenthesis
# Good
foo = (0,)

# Bad
foo = (0, )
  • To align assignment operators
# Good
x = 1
y = 2
long_variable = 3

# Bad
x             = 1
y             = 2
long_variable = 3
  • At the end of a line (known as trailing whitespace). It is usually invisible but can be confusing.

Comments

  • Use docstrings for functions whose purpose may be unclear or that will be used outside of their own modules.
  • Limit the line length of comments and docstrings to 72 characters.
  • Use complete sentences, starting with a capital letter.
  • Use inline comments sparingly.
  • Write inline comments on the same line as the statement they refer to.
  • Separate inline comments by two or more spaces from the statement, and start them with a # and a single space.

"""This is a docstring""".

x = 123  # This is an inline comment.

Boolean value comparison

Avoid comparing boolean values to True or False using ==, instead use if statements.

# Good
if attr:
    print('attr is truthy!')

# Bad
if attr == True:
  print('attr is truthy!')

Supplemental resources: