Python Best Practices — Writing Clean Code
Writing clean, maintainable code is a skill. Follow these practices to write professional Python code.
Learning Objectives
- Follow PEP 8 style guidelines
- Write Pythonic idioms
- Structure projects for maintainability
- Handle errors gracefully
PEP 8 Style
# Naming conventions
class UserManager:
MAX_RETRIES = 3
def get_user(self):
user_name = ""
# Line length: 79 characters max
# Imports: one per line, grouped
import os
import sys
from pathlib import Path
# Whitespace
x = 1
y = x + 1
d = {"key": "value"}
Pythonic Idioms
# 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
with open("file.txt") as f:
data = f.read()
# Use f-strings
message = f"Hello, {name}!"
# EAFP — Easier to Ask Forgiveness than Permission
try:
value = my_dict["key"]
except KeyError:
value = default
Project Structure
# my_project/
# ├── src/
# │ └── my_package/
# │ ├── __init__.py
# │ ├── module1.py
# │ └── module2.py
# ├── tests/
# │ ├── __init__.py
# │ ├── test_module1.py
# │ └── test_module2.py
# ├── pyproject.toml
# ├── README.md
# └── .gitignore
Error Handling
# 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
# Don't catch all exceptions — be specific
Key Takeaways
- Follow PEP 8 for consistent style
- Use Pythonic idioms (enumerate, zip, context managers)
- Be specific with exception handling
- Write docstrings for public functions
- Keep functions small and focused