# 4 spaces per indentation level, never tabsdef func(): if True: do_something()# Max line length: 79 chars (strict PEP 8) or 88 (Black formatter default), team-dependent
# Two blank lines before top-level function/class definitionsdef first_function(): passdef second_function(): passclass MyClass: # One blank line between methods within a class def method_one(self): pass def method_two(self): pass
Imports
# Standard library first, then third-party, then local application imports, each group separated by a blank lineimport osimport sysimport requestsimport pandas as pdfrom my_package import my_module
One import per line for import, grouping allowed for from
import osimport sys # preferred over: import os, sysfrom typing import List, Dict, Optional # fine to group in a single from-import
Comparisons
# Goodif x is None: ...if not items: ...# Avoidif x == None: ...if len(items) == 0: ...
String Quotes
PEP 8 doesn’t mandate single vs double quotes, just consistency. Most modern tooling (Black) defaults to double quotes.
Docstring Conventions
def calculate_total(items, tax_rate=0.0): """Calculate the total cost including tax. Args: items: List of item prices. tax_rate: Tax rate as a decimal (e.g. 0.08 for 8%). Returns: The total cost as a float. """ subtotal = sum(items) return subtotal * (1 + tax_rate)
Automated Tooling (Do This Instead of Manual Checking)
pip install black flake8 isort ruffblack my_file.py # auto-formats code to a consistent styleisort my_file.py # auto-sorts and groups importsflake8 my_file.py # lints for PEP 8 violations and common errorsruff check my_file.py # fast, modern linter, increasingly replacing flake8
Don't manually enforce style, automate it
Running black on save (most editors support this) means you never have to think about spacing or line-wrapping decisions again. Reserve mental effort for logic, not formatting.
The Zen of Python
import this
Prints PEP 20, a short list of guiding principles (“Beautiful is better than ugly”, “Explicit is better than implicit”, “Simple is better than complex”, “Readability counts”). Worth reading once, genuinely.