Coding conventions
suggest changeAdhering to shared coding conventions makes code more readable, maintainable, and idiomatic ("Pythonic"). In the Python ecosystem, style conventions are governed primarily by PEP 8 (Style Guide for Python Code) and guided by the philosophical tenets of the Zen of Python (PEP 20).
1. The Zen of Python (PEP 20)
To view Python's guiding principles, run import this in an interactive Python shell:
import this
Key highlights:
- Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Readability counts.
- There should be one-- and preferably only one --obvious way to do it.
2. Naming Conventions
Python adheres to strict naming conventions to differentiate classes, functions, constants, and internal variables:
| Construct | Convention | Example |
|---|---|---|
| Modules / Packages | Short lowercase, underscores only if needed | os, http_server |
| Classes / Exceptions | PascalCase (CapWords) |
UserAccount, NotFoundError |
| Functions & Methods | snake_case (lowercase with underscores) |
calculate_tax(), get_by_id() |
| Variables & Attributes | snake_case |
user_name, total_count |
| Constants | ALL_CAPS_SNAKE_CASE |
MAX_RETRY_COUNT, DEFAULT_TIMEOUT |
| Protected Internals | Single leading underscore | _internal_cache, _helper() |
| Private (Name Mangles) | Double leading underscore | __private_attr |
| Special / Magic | Dunder (double leading and trailing underscore) | __init__, __repr__, __enter__ |
MAX_CONNECTIONS = 100 # Constant
class DatabasePool: # PascalCase class
def __init__(self, dsn: str):
self.dsn = dsn # Public attribute
self._active_connections = 0 # Protected attribute
def acquire_connection(self): # snake_case method
self._active_connections += 1
return f"Conn from {self.dsn}"
3. Code Layout and Formatting
Indentation
- Use 4 spaces per indentation level.
- Never mix tabs and spaces. Python 3 disallows mixing tabs and spaces for indentation.
Line Length
- Standard PEP 8 recommends a maximum line length of 79 characters for code and 72 characters for docstrings and comments.
- Modern teams and formatters (like Black and Ruff) often configure a line limit of 88 or 100 characters for greater ergonomics on widescreen monitors.
Blank Lines
- Surround top-level function and class definitions with two blank lines.
- Method definitions inside a class are surrounded by one blank line.
- Use blank lines inside functions sparingly to separate logical steps.
4. Organizing Imports
Imports should always be placed at the top of the file, immediately following any module docstrings and comments, and grouped into three distinct sections separated by a single blank line:
"""Module for processing financial invoices."""
# 1. Standard library imports
import os
import sys
from datetime import datetime, timezone
# 2. Related third-party library imports
import requests
from pydantic import BaseModel
# 3. Local application / library specific imports
from myproject.database import get_db_session
from myproject.models import Invoice
Import Rules
- Avoid wildcard imports:
from module import *pollutes the namespace and confuses linters. - Prefer explicit imports:
from math import sqrtorimport math. - Keep imports on separate lines:
# Good import os import sys # Avoid import os, sys
5. Whitespace in Expressions and Statements
Avoid Extraneous Whitespace
# Correct:
spam(ham[1], {eggs: 2})
foo = (0,)
if x == 4: print(x, y); x, y = y, x
# Wrong:
spam( ham[ 1 ], { eggs: 2 } )
foo = (0, )
if x == 4 : print(x , y) ; x , y = y , x
Operators and Assignments
- Always surround binary operators with a single space on either side:
x = 1 total = price + tax is_valid = count > 0 and enabled - Do not use spaces around the
=sign when used to indicate a default keyword argument, unless the parameter has a type annotation (then do use spaces):# Correct: def connect(host, timeout=30): pass def connect(host: str, timeout: int = 30) -> None: pass # Wrong: def connect(host, timeout = 30): pass def connect(host: str, timeout: int=30) -> None: pass
6. Idiomatic Comparisons
Comparison to None
Always use is or is not when testing for None. Never use equality operators (== or !=):
# Correct
if value is None:
print("Value is not set")
if value is not None:
print("Value exists")
# Wrong
if value == None:
pass
Truth Value Testing
Take advantage of Python's built-in truthiness for empty sequences (strings, lists, tuples, dicts):
items = []
# Correct (Pythonic)
if not items:
print("List is empty")
# Unnecessary / Verbose
if len(items) == 0:
print("List is empty")
7. Modern Tooling and Automated Enforcement
Modern Python workflows use automated tools in CI and pre-commit hooks to format and lint code automatically:
- Ruff: An extremely fast Python linter and formatter written in Rust that replaces Flake8, Black, isort, and pydocstyle.
pip install ruff ruff format . # Auto-format files ruff check . # Check lint rules - Black: The uncompromising opinionated code formatter.
- Mypy: Static type checker enforcing PEP 484 type hints.