Python Style Guide
Last updated on 2025-09-26 | Edit this page
Estimated time: 7 minutes
The PEP 8 Style Guide for Python Code gives coding conventions for code layout, comments, naming, and other programming recommendations. The pep8.org website is another presentation of the style guide. By adhering to the Python style guide, developers can write consistent code that is readable and maintainable on small and large projects. Some of the major conventions suggested by the guide are demonstrated below but readers should review the PEP 8 guide for more information.
Indentation
Spaces (not tabs) are the preferred indentation method. Use 4 spaces per indentation level.
Imports
Imports should be on separate lines except when using the from syntax. Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
PYTHON
# Correct
import numpy
import polars
from subprocess import Popen, PIPE
# Wrong
import numpy, polars
Imports should be grouped in the order shown below. An empty line should be placed between each group of imports.
- Standard library imports
- Third party imports
- Local application/library specific imports
PYTHON
# Standard library
import os
import math
# Third party
import numpy as np
import matplotlib.pyplot as plt
# Local package
from mypackage.utils import sayhello
Wildcard imports such as from package import *
should be
avoided because it is unclear what is actually imported from the
package. This confuses both human readers of the code as well as
automated tools.
Documentation strings
Documentation strings, or docstrings, should be written for modules, functions, classes, and methods to describe the associated code. Several docstring styles exist such as the NumPy style and the Google style. The example below uses the Google docstring style.
Naming conventions
Modules should have short lowercase names where underscores can be used to improve readability. Packages should also have short lowercase names but use of underscores is discouraged.
Class names should use the capitalized words (or CapWords, CamelCase) convention.
Function and variable names should be lowercase with underscores to separate words for readability. This naming convention applies to methods on a class object too.
Constants are usually defined at the module level and written in all capital letters.