Follow PEP 8 guidelines for consistent, readable Python code with modern formatting tools.
Follow PEP 8 guidelines for consistent, readable Python code. Use tools like Black and flake8 for automatic formatting and linting.
# ✅ 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 # ✅ 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 Organize imports in the following order with blank lines between groups:
# ✅ 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 from module import *)# ✅ 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} Use these tools to automatically format and lint your Python code:
# pyproject.toml
[tool.black]
line-length = 88
target-version = ['py39']
include = '\.pyi?$'
extend-exclude = '''
/(
# directories
\.eggs
| \.git
| \.mypy_cache
| build
| dist
)/
''' # .flake8
[flake8]
max-line-length = 88
extend-ignore = E203, W503
exclude =
.git,
__pycache__,
.venv,
.eggs,
*.egg,
build,
dist # 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 # 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 # ❌ 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