Master Python Code Style: Practical PEP8 Guidelines and Tools
This guide explains Python's evolving code‑style conventions, emphasizing readability, consistent indentation, line length, spacing, import ordering, and provides an overview of popular linting and formatting tools such as Pylint, Flake8, Isort, Autopep8, Yapf, and Black.
Python's code‑style guide evolves with the language; while older rules fade, new ones appear, and projects often define their own standards. When project conventions clash with generic ones, prioritize the project's guidelines, always aiming for readability as emphasized by Guido and PEP 20.
Consistency is key, especially within a project and its modules, though exceptions exist when strict adherence harms readability, breaks existing structure, predates the guide, or must maintain compatibility with older Python versions.
Code Layout
Indentation
Use four spaces per indentation level.
Inside parentheses you may use vertical implicit indentation or hanging indentation; with hanging indentation the first line contains no parameters.
leapcell_foo = long_function_name(var_one, var_two,
var_three, var_four) # Use extra indentation to distinguish code
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one) # Hanging indentation, extra level required
leapcell_foo = long_function_name(
var_one, var_two,
var_three, var_four)For multi‑line statements, additional indentation is optional, but recommended for clarity, especially with if statements spanning lines.
# No extra indentation
if (this_is_one_thing and
that_is_another_thing):
do_something() # Add comments
# supporting syntax highlighting.
if (this_is_one_thing and
that_is_another_thing):
# Since both conditions are true, we can frobnicate.
do_something() # Recommended extra indentation
if (this_is_one_thing
and that_is_another_thing):
do_something()Spaces and Tabs
Prefer spaces for indentation; use tabs only when aligning with existing tab‑indented code.
Python 3 forbids mixing tabs and spaces; Python 2 warns with -t and errors with -tt. Use pep8 or autopep8 to enforce consistency.
Maximum Line Width
Limit code lines to 79 characters; docstrings and comments to 72 characters. Teams may extend code lines to 80‑100 characters if agreed, but keep comments at 72.
Prefer parentheses, brackets, or braces for line continuation; backslashes are allowed only in specific cases such as with statements.
with open('/path/to/some/file/you/want/to/read') as leapcell_file_1, \
open('/path/to/some/file/being/written', 'w') as leapcell_file_2:
leapcell_file_2.write(leapcell_file_1.read())Binary Operator Continuation
When breaking lines at binary operators, either side can be used, but the Knuth style (break before the operator) is recommended for new code.
leapcell_income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)Blank Lines
Separate top‑level function and class definitions with two blank lines.
Separate method definitions inside a class with one blank line.
Additional blank lines may be used to separate logical blocks, but avoid overuse.
Source File Encoding
Core Python code should use UTF‑8 (ASCII for Python 2).
For ASCII (Python 2) or UTF‑8 (Python 3) files, no encoding declaration is needed; non‑ASCII characters should be expressed with escape sequences.
PEP 3131 recommends ASCII identifiers in the standard library for Python 3+.
Imports
Each import statement occupies its own line; avoid comma‑separated imports.
Place imports at the top of the file after module docstrings, before global variables.
Order imports: standard library, related third‑party libraries, local libraries, separated by blank lines.
Prefer absolute imports for clarity; use relative imports only when the absolute path is excessively long.
Avoid wildcard imports ( from <module> import *) unless re‑exporting an API.
import os
import sys from subprocess import Popen, PIPE import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example from . import sibling
from .sibling import example from myclass import MyClass
from foo.bar.yourclass import YourClass import myclass
import foo.bar.yourclassString Quotes
Single and double quotes are interchangeable; avoid backslashes inside strings when possible.
PEP 257 recommends double quotes for triple‑quoted strings.
Spaces in Expressions and Statements
Avoid spaces inside parentheses; keep commas, colons, and semicolons without preceding spaces.
Do not add extra spaces around assignment or other operators for alignment.
# Correct
spam(ham[1], {eggs: 2})
# Incorrect
spam( ham[ 1 ], { eggs: 2 } ) # Correct trailing comma
leapcell_foo = (0,)
leapcell_bar = (0,)
# Incorrect
leapcell_bar = (0, ) # Correct function call
spam(1)
dct['key'] = lst[index]
# Incorrect
spam (1)
dct ['key'] = lst [index]Code Inspection Tools
Maintaining consistent style and testing standards reduces maintenance burden and improves code quality. The following Python tools help enforce style and formatting.
Code Style Checkers
Pylint : Detects PEP 8 violations and common errors. Install with pip install pylint and run pylint path/to/dir or pylint path/to/module.py. Configuration via pylintrc.
Flake8 : Combines PEP 8, Pyflakes, McCabe, and plugins. Install with pip install flake8 and run flake8 path/to/dir. Supports configuration files and editor integration.
Isort : Sorts imports alphabetically, separating standard, third‑party, and local sections. Install with pip install isort and run isort path/to/module.py. Configurable via .isort.cfg.
Code Formatters
Autopep8 : Automatically formats code to comply with PEP 8. Install with pip install --upgrade autopep8 and run autopep8 --in-place --aggressive --aggressive.
Yapf : Rewrites code for consistent style, even when not strictly violating PEP 8. Install with pip install yapf and run yapf path/to/dir or yapf path/to/module.py.
Black : Opinionated formatter with minimal configuration. Install with pip install black and run black path/to/dir or black path/to/module.py.
Test Coverage Tool
Coverage : Measures test coverage and can output results to the console or HTML. Install with pip install coverage and run coverage run path/to/module.py followed by coverage report -m to see uncovered lines.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Mala Tang
Read source code together, write articles together, and enjoy spicy hot pot together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
