classUserManager: """Manages user operations.""" def__init__(self): self.users = [] defadd_user(self, user): """Add a user to the system.""" self.users.append(user)
defprocess_data(data): """Process incoming data.""" cleaned_data = clean_data(data) results = [] for item in cleaned_data: processed_item = transform_item(item) results.append(processed_item) return results
Naming Conventions
Variables and Functions
Use snake_case for variables and functions
Use descriptive names that explain purpose
1 2 3 4 5 6 7 8 9
# Good user_count = 10 defcalculate_monthly_revenue(): pass
# Bad uc = 10 defcalcMR(): pass
Classes
Use PascalCase for class names
Use nouns that describe what the class represents
1 2 3 4 5 6 7 8 9 10 11 12 13
# Good classUserProfile: pass
classDatabaseConnection: pass
# Bad classuserprofile: pass
classdb_conn: pass
Constants
Use UPPER_SNAKE_CASE for constants
Define at module level
1 2 3 4 5 6 7
# Good MAX_RETRY_ATTEMPTS = 3 DEFAULT_TIMEOUT = 30
# Bad max_retry_attempts = 3 defaultTimeout = 30
Private Members
Use single leading underscore for internal use
Use double leading underscore for name mangling (rare)
1 2 3 4 5 6 7 8 9
classBankAccount: def__init__(self, balance): self.balance = balance self._account_id = self._generate_id() self.__secret_key = self._generate_secret() def_generate_id(self): """Internal method for ID generation.""" pass
defcalculate_compound_interest(principal, rate, time, compound_frequency=12): """Calculate compound interest. Args: principal (float): Initial amount of money. rate (float): Annual interest rate as decimal (e.g., 0.05 for 5%). time (float): Time period in years. compound_frequency (int, optional): Number of times interest compounds per year. Defaults to 12. Returns: float: Final amount after compound interest. Raises: ValueError: If any input values are negative. Example: >>> calculate_compound_interest(1000, 0.05, 2) 1104.89 """ ifany(val < 0for val in [principal, rate, time, compound_frequency]): raise ValueError("All values must be non-negative") return principal * (1 + rate / compound_frequency) ** (compound_frequency * time)
Inline Comments
Use sparingly to explain why, not what
Keep comments up-to-date with code changes
1 2 3 4 5 6 7 8
# Good tax_rate = 0.08# State tax rate for California
# Process only active users to avoid sending emails to deactivated accounts active_users = [user for user in users if user.is_active]
# Bad i += 1# Increment i
Functions & Classes
Function Design
Keep functions small and focused on single responsibility
Use type hints for better code documentation
1 2 3 4 5 6 7 8 9 10 11 12
from typing importList, Optional, Dict
deffilter_active_users(users: List[Dict[str, any]]) -> List[Dict[str, any]]: """Filter list to return only active users.""" return [user for user in users if user.get('is_active', False)]
defget_user_by_id(user_id: int, users: List[Dict[str, any]]) -> Optional[Dict[str, any]]: """Find user by ID, return None if not found.""" for user in users: if user.get('id') == user_id: return user returnNone
This style guide is based on PEP 8 and industry best practices. Consistency within your codebase is more important than strict adherence to any single standard.