Python Best Practices
Write idiomatic, clean Python: PEP 8, naming, project structure, tooling, and common conventions.
What you'll learn
- Follow PEP 8 style guidelines
- Write Pythonic, idiomatic code
- Structure projects professionally
- Use linters and formatters (black, ruff)
- Apply common Python conventions and idioms
Concept
PEP 8 — The Style Guide
PEP 8 is Python's official style guide. Following it makes your code consistent with the entire Python ecosystem. Key rules:
Naming conventions:
snake_case— variables and functions:user_count,calculate_totalUPPER_SNAKE_CASE— constants:MAX_RETRIES,DEFAULT_TIMEOUTPascalCase— classes:MyClass,HttpRequestsnake_case— modules and packages:string_utils,file_handler_private— internal names (convention):_helper_function__dunder__— special methods:__init__,__str__
Formatting:
- 4 spaces per indentation level (never tabs)
- Maximum line length: 79 characters (or 99 for teams that agree)
- Blank lines: 2 between top-level definitions, 1 between methods
- Imports on separate lines
# Good
import os
import sys
# Bad
import os, sys
Import Order
PEP 8 recommends grouping imports in this order:
# 1. Standard library
import os
import sys
from datetime import datetime
# 2. Third-party packages
import requests
import numpy as np
# 3. Local application/modules
from myapp.models import User
from myapp.utils import format_date
Separate each group with a blank line. Sort alphabetically within each group.
Writing Pythonic Code
Pythonic means using Python's idioms and conventions naturally. Compare:
# Unpythonic — C/Java style
numbers = [1, 2, 3, 4, 5]
total = 0
for i in range(len(numbers)):
total += numbers[i]
# Pythonic — use built-in sum
total = sum(numbers)
# Unpythonic — manual index
for i in range(len(fruits)):
print(fruits[i])
# Pythonic — iterate directly
for fruit in fruits:
print(fruit)
# Unpythonic — manual index tracking
index = 0
for fruit in fruits:
print(index, fruit)
index += 1
# Pythonic — use enumerate
for index, fruit in enumerate(fruits):
print(index, fruit)
The Zen of Python
Run import this in Python to see 20 guiding principles. The most important:
- Beautiful is better than ugly
- Explicit is better than implicit
- Simple is better than complex
- Readability counts
- There should be one obvious way to do it
These principles guide every design decision in Python. When in doubt, choose the simpler, more readable solution.
Common Idioms
# Check for empty collections — use truthiness, not len()
if my_list: # good — non-empty
...
if not my_string: # good — empty string
...
# Swap variables
a, b = b, a
# Multiple assignment
x = y = z = 0
# Unpacking
first, *rest = my_list
# Default dict values
name = user.get("name", "Anonymous")
# Ternary expression
status = "adult" if age >= 18 else "minor"
# Chained comparisons
if 0 <= score <= 100: # instead of 0 <= score and score <= 100
...
# String joining (not + concatenation in loops)
result = ", ".join(words) # efficient
Project Structure
A professional Python project:
myproject/
├── pyproject.toml # project config (modern standard)
├── README.md # documentation
├── .gitignore
├── src/
│ └── myproject/
│ ├── __init__.py
│ ├── cli.py # entry point
│ ├── core.py # main logic
│ └── utils.py # helpers
├── tests/
│ ├── test_core.py
│ └── conftest.py
└── docs/
└── ...
The src/ layout prevents accidental imports from the working directory. pyproject.toml replaces setup.py for modern projects.
Tooling
black — Code Formatter
pip install black
black my_script.py # format in place
black formats your code automatically — no debates about style. It is opinionated and uncompromising, which eliminates bikeshedding. Just run it and move on.
ruff — Fast Linter
pip install ruff
ruff check my_script.py # lint
ruff check --fix . # lint and auto-fix
ruff is an extremely fast linter (written in Rust) that replaces flake8, isort, and many other tools. It catches style violations and common bugs.
mypy — Type Checker
pip install mypy
mypy my_script.py
mypy checks type hints statically, catching type errors before runtime.
The Modern Toolchain
# Format
black .
# Lint and fix
ruff check --fix .
# Type check
mypy src/
# Test
pytest
Set up these tools to run automatically on save (via your editor) and in CI. They catch problems early and enforce consistency.
Documentation
def calculate_bmi(weight: float, height: float) -> float:
"""Calculate Body Mass Index.
The BMI is defined as weight in kilograms divided by
the square of height in meters.
Args:
weight: Weight in kilograms (must be positive).
height: Height in meters (must be positive).
Returns:
The BMI value.
Raises:
ValueError: If weight or height is not positive.
Example:
>>> calculate_bmi(70, 1.75)
22.857...
"""
if weight <= 0 or height <= 0:
raise ValueError("Weight and height must be positive")
return weight / (height ** 2)
Good docstrings explain:
- What the function does (one line)
- Why (if not obvious)
- Parameters and their expected types
- Return value
- Exceptions that might be raised
- Examples (doctests)
Key Principles
- Readability over cleverness — code is read more than it is written
- Explicit is better than implicit — do not hide behavior
- One responsibility per function — small, focused functions
- Fail fast — validate inputs early, raise clear errors
- DRY but not over-abstracted — avoid premature abstraction
- Test your code — untested code is broken code
- Use the standard library — do not reinvent the wheel
- Follow PEP 8 — consistency with the ecosystem
Example
# --- PEP 8 compliant code ---
# Constants in UPPER_SNAKE_CASE
MAX_RETRIES = 3
DEFAULT_TIMEOUT = 30
# Imports: standard, third-party, local (with blank lines between)
import os
import sys
from datetime import datetime
import requests
from myapp.utils import format_date
# Classes in PascalCase
class User:
"""Represents a user in the system."""
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def __repr__(self) -> str:
return f"User(name={self.name!r}, age={self.age})"
# Functions in snake_case with type hints and docstrings
def calculate_average(numbers: list[float]) -> float:
"""Calculate the arithmetic mean of a list of numbers.
Args:
numbers: A non-empty list of numbers.
Returns:
The arithmetic mean.
Raises:
ValueError: If the list is empty.
"""
if not numbers:
raise ValueError("Cannot calculate average of empty list")
return sum(numbers) / len(numbers)
# Pythonic idioms
def demonstrate_idioms():
fruits = ["apple", "banana", "cherry"]
# Enumerate instead of manual index
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Truthiness check instead of len()
if fruits:
print(f"First fruit: {fruits[0]}")
# Ternary expression
count = len(fruits)
label = "fruit" if count == 1 else "fruits"
print(f"{count} {label}")
# Dict comprehension
lengths = {f: len(f) for f in fruits}
print(f"Lengths: {lengths}")
# Join instead of concatenation
print(", ".join(fruits))
# Context manager for resource management
def read_config(filename: str) -> dict:
"""Read a configuration file safely."""
with open(filename, encoding="utf-8") as f:
import json
return json.load(f)
# Main guard
if __name__ == "__main__":
demonstrate_idioms()
print(f"Average: {calculate_average([1.0, 2.0, 3.0, 4.0])}")
Shows PEP 8 compliant code: constants, import ordering, PascalCase class, snake_case function with type hints and docstring, Pythonic idioms (enumerate, truthiness, ternary, comprehension, join), context manager, and the __name__ guard.
Try it
- JSON Formatter
Well-formatted JSON follows the same principles as well-formatted code.
- Case Converter
PEP 8 naming conventions — convert identifiers to the right case.
Common mistakes
The mistake
Writing non-Pythonic code with manual index loops instead of using enumerate or direct iteration
The fix
Use 'for item in collection' for direct iteration, 'for i, item in enumerate(collection)' for index+value, and 'for key, value in dict.items()' for dicts. Avoid range(len(...)) — it is a C/Java pattern, not Pythonic.
The mistake
Not using a formatter and linter, leading to inconsistent style across the codebase
The fix
Set up black (formatter) and ruff (linter) to run automatically on save. black eliminates all style debates by formatting code deterministically. ruff catches style violations and common bugs. Configure your editor to run them on save.
Related Resources
Related Cheatsheets
- Python Cheatsheet
PEP 8 rules, idioms, and project structure reference.
Practice Python Best Practices
2 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.