Python Coding Standards (PEP 8)
PEP 8 is the style guide for Python code. It provides guidelines and best practices on how to write Python code to maximize readability and consistency.
Indentation
- Use 4 spaces per indentation level.
- Do not use tabs.
# Correct:
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
# Wrong:
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
Maximum Line Length
- Limit all lines to a maximum of 79 characters.
- For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.
Blank Lines
- Surround top-level function and class definitions with two blank lines.
- Method definitions inside a class are surrounded by a single blank line.
class MyClass:
def first_method(self):
return None
def second_method(self):
return None
Imports
- Imports should usually be on separate lines.
- Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
Order of Imports:
- Standard library imports.
- Related third-party imports.
- Local application/library specific imports.
import os
import sys
from flask import Flask
import my_local_module
Whitespace in Expressions and Statements
- Avoid extraneous whitespace inside parentheses, brackets, or braces.
# Correct:
spam(ham[1], {eggs: 2})
# Wrong:
spam( ham[ 1 ], { eggs: 2 } )
- Always surround these binary operators with a single space on either side: assignment (
=), augmented assignment (+=,-=etc.), comparisons (==,<,>,!=,<=,>=,in,not in,is,is not), Booleans (and,or,not).
Naming Conventions
- Variables and Functions:
snake_case(lowercase with underscores). - Classes:
CapWords(CamelCase). - Constants:
ALL_CAPS(uppercase with underscores). - Private Members:
_single_leading_underscore(internal use) or__double_leading_underscore(name mangling).