Python Best Practices — Writing Clean Code
Writing clean, maintainable code is a skill that separates junior from senior developers. Follow these practices to write professional Python code.
Learning Objectives
- Follow PEP 8 style guidelines consistently
- Write Pythonic idioms that leverage language features
- Structure projects for maintainability and scalability
- Handle errors gracefully with proper exception hierarchy
PEP 8 Style Guide
The foundation of Python code style:
# Naming conventions
class UserManager: # CamelCase for classes
MAX_RETRIES = 3 # UPPER_CASE for constants
def get_user(self): # snake_case for functions/methods
user_name = "" # snake_case for variables
# Line length: 79 characters max (72 for docstrings)
# Imports: one per line, grouped (stdlib, third-party, local)
import os
import sys
from pathlib import Path
from flask import Flask
from sqlalchemy import Column
from myapp.models import User
# Whitespace matters
x = 1
y = x + 1
d = {"key": "value"}
lst = [1, 2, 3]
Pythonic Idioms
Write idiomatic Python that leverages the language:
# Use enumerate instead of manual index
for i, item in enumerate(items):
print(i, item)
# Use zip for parallel iteration
for name, score in zip(names, scores):
print(f"{name}: {score}")
# Use any/all for boolean checks
if any(x > 10 for x in numbers):
print("Found large number")
# Use context managers (always!)
with open("file.txt") as f:
data = f.read()
# Use f-strings (Python 3.6+)
message = f"Hello, {name}!"
# EAFP — Easier to Ask Forgiveness than Permission
try:
value = my_dict["key"]
except KeyError:
value = default
# Use unpacking
first, *middle, last = [1, 2, 3, 4, 5]
# first=1, middle=[2,3,4], last=5
SOLID Principles
Apply these object-oriented design principles:
| Principle | Meaning | Example |
|---|---|---|
| Single Responsibility | One class = one job | User class handles users, not email sending |
| Open/Closed | Open for extension, closed for modification | Use abstract base classes |
| Liskov Substitution | Subtypes must be substitutable | Dog subclass works where Animal expected |
| Interface Segregation | Small, specific interfaces | Separate Readable and Writable |
| Dependency Inversion | Depend on abstractions | Use ABC, not concrete classes |
Project Structure
Organize code for maintainability:
Error Handling Best Practices
Be specific and informative:
# Be specific with exceptions
try:
result = risky_operation()
except ValueError as e:
logger.error(f"Value error: {e}")
raise
except ConnectionError:
logger.error("Connection failed")
return fallback_value
# Create custom exceptions for your domain
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(
f"Insufficient funds: balance={balance}, requested={amount}"
)
# Don't catch all exceptions — be specific
# BAD: except Exception:
# GOOD: except (ValueError, TypeError) as e:
Documentation Standards
Write clear, useful documentation:
def calculate_discount(price: float, discount: float) -> float:
"""Calculate discounted price.
Args:
price: Original price (must be positive)
discount: Discount percentage (0.0 to 1.0)
Returns:
Price after discount
Raises:
ValueError: If discount is not between 0 and 1
Example:
>>> calculate_discount(100.0, 0.2)
80.0
"""
if not 0 <= discount <= 1:
raise ValueError(f"Discount must be 0-1, got {discount}")
return price * (1 - discount)
Code Review Checklist
Before submitting code, verify:
- Functions do one thing (Single Responsibility)
- Names are descriptive (no
x,tmp,data) - No duplicated code (DRY principle)
- Error handling is specific (not bare
except:) - Public functions have docstrings
- Tests cover edge cases
- No hardcoded values (use constants or config)
- Imports are organized (stdlib -> third-party -> local)
Common Mistakes
| Mistake | Problem | Better Approach |
|---|---|---|
| Mutable default args | def f(x=[]) | def f(x=None) then x = x or [] |
| Bare except | Catches everything | Catch specific exceptions |
| Global state | Hard to test and debug | Pass dependencies explicitly |
| Over-abstraction | Unnecessary complexity | Keep it simple (YAGNI) |
| Premature optimization | Optimize before profiling | Profile first, optimize second |
Key Takeaways
- Follow PEP 8 for consistent style — use
blackformatter to automate - Use Pythonic idioms: enumerate, zip, context managers, f-strings, EAFP
- Be specific with exception handling — never use bare
except: - Write docstrings for all public functions — Google or NumPy style
- Keep functions small and focused — one function = one job
- Use type hints to catch bugs early and improve IDE support
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions