Back to Blog
"Python Coding Best Practices" title over a blue binary-code background with the Python logo
Engineering
Dec 3, 2018
4 Min Read

Python Coding Best Practices

Python is one of the most widely used languages today, and following a consistent set of conventions benefits both you and anyone else who works with your code later. Below are the coding standards the Machine Learning Team at FCode Labs uses for their Python projects.

Naming Conventions

  • Class names should use UpperCamelCase.
  • Variable names should use snake_case.
  • Constants should use UPPER_CASE.
  • Function names should use snake_case.
  • The first argument of a class’s methods should be self.
  • Private variable and method names should start with two underscores (__).
  • Protected variable and method names should start with a single underscore (_).
  • All class variables, whether public, protected, or private, should be defined inside __init__(), or inside a method called from __init__(). That helper method should be private. (Think about why: hint, polymorphism.)
first_variable = 10

CONSTANT_VARIABLE = 20


class MyClass(object):
    second_variable = 10

    def __init__(self):
        self.public_variable = 3
        self._protected_variable = 4
        self.__private_variable = 5

    def public_method(self, arg_one):
        return self.__private_method(arg_one + 1)

    def __private_method(self, arg_one):
        arg_two = arg_one * arg_one
        return arg_two

Programming Rules

  • When comparing against None, always use is, never ==.
  • Don’t wrap if conditions in parentheses, except where needed for operator precedence.
# Avoid
if x == None and y != None:
    pass

# Prefer
if x is None and y is not None:
    pass

# Parentheses are fine here because they are needed for precedence
if (x + 1) / 10 == y:
    pass
  • If a class has no other base class, it should still inherit explicitly from object.
class MyClass(object):
    pass
  • Use not in for membership checks, rather than negating in.
a = [1, 2, 3]

# Avoid
if not 10 in a:
    pass

# Prefer
if 10 not in a:
    pass
  • Group imports in the following order:
    1. Standard library imports.
    2. Related third-party imports.
    3. Local application/library-specific imports.
import os
import sys
import threading

import cv2
import tensorflow as tf

import zmlvideo
import mymodule

Documentation and Formatting

Docstrings

  • Enclose docstrings in triple double quotes (""").
  • Use the spacing shown in the example below when writing a docstring.
def some_function(arg1, arg2):
    """
    You can describe the function in a docstring.
    You can specify descriptions for the arguments and the return value.
    You can also document the return type.

    :param arg1: the first argument
    :param arg2: the second argument
    :return: the addition of two arguments
    :rtype: int
    """
    return arg1 + arg2

Whitespace and Layout

  • Indent with four spaces and never use tabs.
  • Put one space on each side of the = sign when assigning a value to a variable.
  • Put one space on each side of every operator.
  • When passing keyword arguments or setting default parameter values, don’t put spaces around the = sign.
  • Put a space after every comma.
  • Separate top-level functions and classes with two blank lines.
  • Separate methods within a class with a single blank line.
  • Don’t use more than one blank line to separate blocks of code within a function or method body.
  • Leave at least two spaces between the end of a line of code and an inline comment.
  • Leave a single space after the # and before the comment text begins.
def some_function(arg1, arg2):
    # Space is used around operators
    return arg1 + arg2  # At least 2 spaces before an inline comment


class FirstClass(object):  # 2 blank lines before a class
    def __init__(self):
        self._value = self.__get_value(arg1=2, arg2=10)
        # A single blank line separates methods

    def __get_value(self, arg1, arg2=3):  # No spaces around '=' for default args
        return arg1 * arg2

Following these conventions keeps the codebase consistent and easier for the whole team to read, review, and maintain.

Filed Under

Join the Conversation

This dispatch is part of an ongoing series on the future of intelligence. Share your perspective or subscribe for more.

Weekly dispatches. No spam. Ever.