Sign In Create Account
Formatting & PEP 8

Code Formatting & PEP 8

Follow PEP 8 guidelines for consistent, readable Python code with modern formatting tools.

Core Formatting Rules

Follow PEP 8 guidelines for consistent, readable Python code. Use tools like Black and flake8 for automatic formatting and linting.

  • • Use 4 spaces for indentation (never tabs)
  • • Limit lines to 88 characters (Black's default) or 79 (PEP 8)
  • • Use snake_case for variables and functions
  • • Use PascalCase for classes
  • • Use UPPER_SNAKE_CASE for constants

Formatting Examples

# ✅ Good formatting and naming
MAX_RETRY_ATTEMPTS = 3
DEFAULT_TIMEOUT = 30

class UserManager:
    """Manages user operations and authentication."""
    
    def __init__(self, database_url: str):
        self.database_url = database_url
        self._connection = None
    
    def authenticate_user(self, username: str, password: str) -> bool:
        """Authenticate user with provided credentials."""
        if not username or not password:
            return False
        
        user_record = self._fetch_user_by_username(username)
        return self._verify_password(user_record, password)
    
    def _fetch_user_by_username(self, username: str) -> dict:
        """Private method to fetch user from database."""
        # Implementation details
        pass
    
    def _verify_password(self, user_record: dict, password: str) -> bool:
        """Private method to verify user password."""
        # Implementation details
        pass

PEP 8 Benefits

  • Consistency: Code looks the same across projects
  • Readability: Easier for team members to understand
  • Maintainability: Reduces cognitive load when making changes
  • Professional Standard: Industry-wide accepted conventions

Function and Class Formatting

Function Formatting

# ✅ Good function with proper spacing
def calculate_shipping_cost(
    weight: float,
    distance: float,
    shipping_method: str = "standard"
) -> float:
    """Calculate shipping cost based on weight, distance, and method."""
    base_cost = 5.0
    weight_multiplier = 0.1
    distance_multiplier = 0.05
    
    if shipping_method == "express":
        base_cost *= 2
    
    return base_cost + (weight * weight_multiplier) + (distance * distance_multiplier)

# ✅ Class with proper method spacing
class PaymentProcessor:
    """Process various types of payments."""
    
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.session = self._create_session()
    
    def process_payment(self, amount: float, method: str) -> dict:
        """Process a payment and return transaction details."""
        if method == "credit_card":
            return self._process_credit_card(amount)
        elif method == "paypal":
            return self._process_paypal(amount)
        else:
            raise ValueError(f"Unsupported payment method: {method}")
    
    def _create_session(self):
        """Create authenticated session for API calls."""
        # Implementation
        pass

Import Organization

Organize imports in the following order with blank lines between groups:

Import Organization

# ✅ Proper import organization
# 1. Standard library imports
import os
import sys
from datetime import datetime, timedelta
from pathlib import Path

# 2. Related third-party imports
import requests
from django.db import models
from flask import Flask, request, jsonify

# 3. Local application/library imports
from myapp.models import User
from myapp.utils import validate_email
from .exceptions import InvalidUserError

Import Best Practices

  • • Use absolute imports when possible
  • • Avoid wildcard imports (from module import *)
  • • Group imports logically and alphabetically within groups
  • • Use parentheses for long import lists

Whitespace and Line Breaking

Whitespace Guidelines

# ✅ Good whitespace usage
def complex_function(param_one, param_two, param_three):
    """Function with proper spacing."""
    # Two blank lines before top-level functions and classes
    
    # One blank line between methods
    result = calculate_something(param_one)
    
    # Space around operators
    total = result + param_two * param_three
    
    # No space before commas, colons, semicolons
    my_dict = {'key': 'value', 'another': 'item'}
    my_list = [1, 2, 3, 4, 5]
    
    # Space after commas, colons, semicolons
    if condition:
        do_something()
    
    return total

# ✅ Long line breaking
def function_with_long_parameters(
    first_parameter: str,
    second_parameter: int,
    third_parameter: bool = False,
    fourth_parameter: list = None
) -> dict:
    """Function with long parameter list."""
    if fourth_parameter is None:
        fourth_parameter = []
    
    # Long dictionary
    config = {
        'database_url': 'postgresql://user:pass@localhost/db',
        'api_endpoint': 'https://api.example.com/v1/',
        'timeout_seconds': 30,
        'retry_attempts': 3,
    }
    
    # Long list
    allowed_methods = [
        'GET', 'POST', 'PUT', 'DELETE',
        'PATCH', 'HEAD', 'OPTIONS'
    ]
    
    return {'config': config, 'methods': allowed_methods}

Automated Formatting Tools

Use these tools to automatically format and lint your Python code:

Black - Code Formatter

Black Configuration

# pyproject.toml
[tool.black]
line-length = 88
target-version = ['py39']
include = '\.pyi?$'
extend-exclude = '''
/(
  # directories
  \.eggs
  | \.git
  | \.mypy_cache
  | build
  | dist
)/
'''

Flake8 - Linter

Flake8 Configuration

# .flake8
[flake8]
max-line-length = 88
extend-ignore = E203, W503
exclude = 
    .git,
    __pycache__,
    .venv,
    .eggs,
    *.egg,
    build,
    dist

isort - Import Sorter

isort Configuration

# pyproject.toml
[tool.isort]
profile = "black"
multi_line_output = 3
line_length = 88
include_trailing_comma = true
force_grid_wrap = 0
combine_as_imports = true
ensure_newline_before_comments = true

Tool Integration

# Install formatting tools
pip install black flake8 isort

# Format code
black .
isort .

# Check formatting
flake8 .

# Pre-commit hook setup
pip install pre-commit
# Create .pre-commit-config.yaml with black, flake8, isort

Common Formatting Mistakes

Formatting Mistakes to Avoid

# ❌ Bad formatting examples
def badFunction( x,y ):  # Wrong spacing and naming
    z=x+y  # No spaces around operators
    return z

class badClass:  # Bad class naming
    def __init__( self ):  # Wrong spacing
        pass
        
# ❌ Bad imports
from os import *  # Wildcard import
import sys,os  # Multiple imports on same line

# ❌ Bad whitespace
def bad_function():
    
    # Too many blank lines above
    x=1+2+3  # No spaces around operators
    my_list=[1,2,3,4]  # No spaces after commas
    
    if x==6:  # No spaces around comparison
        return True
    
# ❌ Bad line breaking
def function_with_too_long_line(parameter_one, parameter_two, parameter_three, parameter_four):
    return parameter_one + parameter_two + parameter_three + parameter_four

Common Issues

  • Inconsistent Indentation: Mixing tabs and spaces
  • Too Long Lines: Lines exceeding character limits
  • Poor Naming: Using camelCase instead of snake_case
  • Bad Spacing: Inconsistent whitespace around operators