Skip to content

Latest commit

 

History

History
137 lines (99 loc) · 3.43 KB

Python.md

File metadata and controls

137 lines (99 loc) · 3.43 KB

Python Style Guide python3

This is a style guide for writing code in Python 3.

Flake8 Style Guide

As a base guide, the Flake8 Style Guide should be followed.

Note: Flake8 is a wrapper around the following linting tools:

Binary Operator Line Breaks

When splitting statements over multiple lines, line breaks should occur before binary operators

Example:

first_number
+ second_number
- third_number

Example:

first_boolean
and second_boolean
and (
    third_boolean
    or not fourth_boolean
)

Multiline if-statements

When the conditional of an if-statement needs to be split over multiple lines, it should adhere to the following format:

if (
    this_is_one_thing
    and this_is_another_thing
):
    do_stuff()
    do_some_other_stuff()

Imports

PEP 8 specifies three different import groups each separated by a blank line:

  1. Standard library imports.
  2. Related third party imports.
  3. Local application/library specific imports.

Within each of these groups, imports should be sorted alphabetically.

Example:

import os
import sys

from requests import Session
import yaml

import local_module
from second_local_module import first_thing, second_thing, third_thing
import z_another_local_module

Docstrings

Python Docstrings may be used to add documentation to Python code. The reStructuredText (reST) Docstring Format is the preferred docstring format.

Related Tools

  • Visual Studio Code: autoDocstring plugin. Add "autoDocstring.docstringFormat": "sphinx" to your settings.json
  • Vim: vim-pydocstring plugin. Uses reST by default.
  • Command Line: pyment. Uses reST output docstring format by default.

Examples

Basic example

def sum(a, b):
    """Computes the sum of two numbers

    :param a: The first number
    :param b: The second number
    :returns: The sum of a and b
    """
    return a + b

Example with types

from types import number


def sum(a: number, b: number) -> number:
    """Computes the sum of two numbers

    :param number a: The first number
    :param number b: The second number
    :returns: The sum of a and b
    :rtype: number
    """
    return a + b

Note: Parameter types can also be placed on separate lines:

    :param a: The first number
    :type a: number

but return types must be on a separate line using :rtype

Quoting Strings

Strings should be single-quoted when possible. When single quotation marks are required in a string, the string should be double-quoted and the single quotation marks should be unescaped. When accessing a dictionary within an f-string, the string should be double-quoted and the dictionary keys should be single-quoted.

Examples

"A string with 'quoted examples'"
f"{obj['prop_a']['prop_b']} and {obj_2['prop_c']} are values"