Skip to content

Python Style

Tianshu Huang edited this page Sep 19, 2018 · 1 revision

Python Style & Standards

Python code should conform to the PEP-8 standard and use numpy-style docstrings.

What is PEP-8?

PEP-8 is the style guide used by Python's standard libraries. First written in 2001, this document prescribes a golden standard for all python formatting.

A good way to get used to PEP-8 is to install a strict linter for your text editor of choice. For example, Anaconda for Sublime Text includes both a syntax linter and a PEP-8 style linter.

The full specifications for PEP-8 can be found on the python website.

PEP-8 Basics

The most important rules are:

  • Maximum of 79 characters per line
  • Four spaces per indentation level
  • Continuation lines and hanging indents aligned with the opening delimiter or on a new line with an additional level of indentation: (example taken from the official PEP-8 documentation)
# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# More indentation included to distinguish this from the rest.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

# Hanging indents should add a level.
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)
  • Two empty lines between top-level function and class definitions
  • One empty line between class methods
  • At most one consecutive blank line within functions and methods to separate logical sections
  • Functions and variables in lower_case_with_underscores
  • Classes in UpperCamelCase
  • Constants in ALL_CAPS_WITH_UNDERSCORES

Extra rules

These rules are not mandated by PEP-8.

  • Files must be shorter than 300 lines, except for configuration files. If possible, keep files shorter than 250 lines.
  • Functions should be shorter than 50 lines where possible.
  • File names should be in lower_case_with_underscores.py.

Numpy-style Docstrings

Numpy-style docstrings are primarily established for Numpy's documentation. Due to widespread adoption and community support, documentation can directly generated from these docstrings without requiring clunkly directives or special commands.

With sphinx and napoleon installed, and a sphinx project setup with sphinx-quickstart, documentation can be generated directly from source code with the following command:

sphinx-apidoc -f -o source/target path/to/code/directory

You can find an example of Numpy-style docstrings in action here.

The general format of docstrings is:

def example(variable_name, example_param):
    """Short summary of function

    Extended description of function (optional); this can span several lines
    if the function is sufficiently complicated.

    Parameters
    ----------
    variable_name : str
        Description of variable
    example_param : int
        Another descriptiion. Two backquotes can be used to surround code
        snippets (equivalent to three backquotes in markdown) like ``this``.

    Returns
    -------
    bool
        Description of return value

    Examples
    --------
    This optional section can be used to provide sample usage of the function
    or method.

        >>> print(example("foo", 3))
        True

    """

    return len(variable_name) == example_param

Dividers

Configuration files and other long source files can use decorative dividers to create a visual separation between blocks of code. This should not be necessary for ordinary source code.

Large divider:

# -----------------------------------------------------------------------------
#
#                               Divider Caption
#
# -----------------------------------------------------------------------------

Small divider:

# -- Divider Caption ----------------------------------------------------------

Clone this wiki locally