Python Best Practices β Complete Learning Series
Learn Python best practices step by step using practical examples from real-world backend developmentβespecially FastAPI applications and multi-tenant SaaS systems.
How Every Topic Is Structured
- Bad practice: How developers commonly write code incorrectly.
- Best practice: How we should write it.
- Why? Why the recommended approach is better.
- Real-world example: Where to use it in production backends.
Learning Roadmap (18 Core Topics)
| # | Topic | Importance |
|---|---|---|
| 1 | Naming conventions | Essential |
| 2 | Variables and constants (avoid unnecessary globals) | Essential |
| 3 | Functions and parameters (mutable defaults) | Essential |
| 4 | Avoid code duplication (DRY) & early returns | Essential |
| 5 | Type hints | Essential |
| 6 | Exception handling (don't catch every exception) | Essential |
| 7 | Logging instead of print() | Essential |
| 8 | Avoid mutable default arguments (deep dive) | Critical |
| 9 | Context managers (with) | Important |
| 10 | Separate business logic from API logic | Essential |
| 11 | SOLID principles | Advanced |
| 12 | Dependency injection | Advanced |
| 13 | Classes and dataclasses vs Pydantic | Important |
| 14 | Async/await best practices | Essential for FastAPI |
| 15 | Database and transaction handling | Essential |
| 16 | Security best practices | Critical |
| 17 | Project structure | Essential |
| 18 | Testing and mocking | Essential |
Lesson 1: Naming Conventions Essential
Python has established naming conventions defined in PEP 8.
1.1 Variable naming
x = "Murugan"
y = 25
z = True
What's wrong?
- What does
xrepresent? - What does
yrepresent? - What does
zrepresent? - Other developers cannot easily understand the purpose.
customer_name = "Murugan"
customer_age = 25
is_active = True
Why? Readable code reduces maintenance costs and makes debugging easier. Python convention uses snake_case for variables and functions.
1.2 Function naming
def GetCustomer(id):
pass
def addProduct():
pass
def get_customer(customer_id):
pass
def add_product(product):
pass
| Python | Java / Kotlin |
|---|---|
get_customer() | getCustomer() |
customer_name | customerName |
CustomerService | CustomerService |
1.3 Class naming
class customer_service:
pass
class CustomerService:
pass
Python uses PascalCase for classes.
1.4 Boolean naming
active = True
deleted = False
is_active = True
is_deleted = False
has_permission = True
can_edit = False
Why? Boolean names should communicate a condition so code reads almost like natural English:
if customer.is_active:
process_order()
Lesson 2: Avoid Unnecessary Global Variables Essential
This is a particularly important practice in backend applications.
total_amount = 0
def add_amount(amount):
global total_amount
total_amount += amount
What's wrong?
- Any function can accidentally modify the global variable.
- Functions become dependent on external state.
- Unit testing becomes harder.
- Concurrent requests can introduce race conditions.
def add_amount(current_total: float, amount: float) -> float:
return current_total + amount
total = add_amount(100.0, 50.0)
print(total) # 150.0
Why? The function receives its dependencies through parameters and returns its result, making it predictable and easy to test.
public double addAmount(double current, double amount) {
return current + amount;
}
MAX_RETRY_COUNT = 3) are perfectly reasonable.
Lesson 3: Never Use Mutable Default Arguments Critical
def add_product(product, products=[]):
products.append(product)
return products
print(add_product("Laptop")) # ['Laptop']
print(add_product("Mobile")) # ['Laptop', 'Mobile']
Why does this happen? Python evaluates default arguments only once, when the function is defined. Therefore, the same list is reused across function calls.
def add_product(product, products=None):
if products is None:
products = []
products.append(product)
return products
print(add_product("Laptop")) # ['Laptop']
print(add_product("Mobile")) # ['Mobile']
list, dict, or set as default function arguments. Use None instead.
Lesson 4: Use Type Hints Essential
If you come from Java or Kotlin, you'll appreciate this practice.
def calculate_total(price, quantity):
return price * quantity
- What type is
price? - What type is
quantity? - What does the function return?
- IDE support and static analysis are less effective.
def calculate_total(
price: float,
quantity: int
) -> float:
return price * quantity
def get_customer(customer_id: str) -> dict:
pass
def is_customer_active(customer_id: str) -> bool:
pass
def get_products() -> list[str]:
return ["Laptop", "Mobile"]
For optional / nullable return types:
from typing import Optional
def get_customer(customer_id: str) -> Optional[dict]:
return None
# Modern Python (3.10+) also supports:
def get_customer(customer_id: str) -> dict | None:
return None
Lesson 5: Avoid Unnecessary else Statements Essential
def get_discount(customer):
if customer.is_premium:
return 20
else:
return 5
def get_discount(customer):
if customer.is_premium:
return 20
return 5
Why? Once Python executes return, the function ends. The else is unnecessary. This is called an early return or guard-clause style.
def update_customer(customer):
if customer is None:
return False
if not customer.is_active:
return False
# Perform update
return True
This avoids deeply nested conditions and improves readability.
Lesson 6: Don't Catch Every Exception Essential
def divide(a, b):
try:
return a / b
except:
return None
- It catches almost every exception (even
KeyboardInterruptorSystemExit). - Programming errors (like
TypeError) can be hidden. - Debugging becomes difficult and useful error information is lost.
def divide(a: float, b: float) -> float:
try:
return a / b
except ZeroDivisionError:
raise ValueError("Divisor cannot be zero")
from fastapi import HTTPException
def get_customer(customer_id: str):
customer = find_customer(customer_id)
if customer is None:
raise HTTPException(
status_code=404,
detail="Customer not found"
)
return customer
For larger applications, keep HTTP exception handling in the API layer and business exceptions in the service layer.
Lesson 7: Use Logging Instead of print() Essential
def create_customer(customer):
print("Creating customer...")
print(customer)
import logging
logger = logging.getLogger(__name__)
def create_customer(customer):
logger.info("Creating customer")
# Business logic
| Level | Purpose |
|---|---|
DEBUG | Detailed debugging information |
INFO | Normal application events |
WARNING | Unexpected but recoverable situations |
ERROR | Operation failed |
CRITICAL | Serious application failure |
try:
create_customer(customer)
except Exception:
logger.exception("Failed to create customer")
raise
logger.exception() automatically includes the full exception traceback.
Lesson 8: Mutable Default Arguments (Deep Dive) Critical
The Problem
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("Apple")) # ['Apple']
print(add_item("Orange")) # ['Apple', 'Orange']
print(add_item("Mango")) # ['Apple', 'Orange', 'Mango']
You can verify that Python reuses the exact same object across calls:
def test(value=[]):
value.append(1)
print(id(value))
test()
test()
test() # All three print the same object ID!
Correct Approach
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
Another Example with Dictionaries
def create_user(name, metadata={}):
metadata["name"] = name
return metadata
def create_user(name, metadata=None):
if metadata is None:
metadata = {}
metadata["name"] = name
return metadata
list, dict, and set. Immutable defaults such as str, int, and tuple are safe.
Lesson 9: Use Context Managers (with) Important
Context managers manage resources automaticallyβsuch as files, database connections, locks, network connections, and transactions.
Example 1: File Handling
file = open("data.txt", "w")
file.write("Hello Python")
file.close() # May not run if an exception occurs!
with open("data.txt", "w", encoding="utf-8") as file:
file.write("Hello Python")
Example 2: Multiple Files
with (
open("input.txt", encoding="utf-8") as source,
open("output.txt", "w", encoding="utf-8") as destination
):
content = source.read()
destination.write(content)
Example 3: Custom Context Managers
class DatabaseConnection:
def __enter__(self):
print("Database connected")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Database disconnected")
with DatabaseConnection() as db:
print("Executing query")
Or using contextlib with try / finally so cleanup always runs even when an exception occurs:
from contextlib import contextmanager
@contextmanager
def database_connection():
print("Connecting")
try:
yield
finally:
print("Disconnecting")
with database_connection():
print("Executing query")
Lesson 10: Separate Business Logic from API Logic Essential
This is especially important for FastAPI + Firestore multi-tenant SaaS applications.
@app.post("/products")
async def create_product(product: dict):
if product["price"] <= 0:
raise HTTPException(400, "Invalid price")
db.collection("products").add(product)
return {"message": "Created"}
- HTTP handling and business rules are mixed.
- Database access is mixed with business logic.
- Unit testing and reusing business logic become difficult.
Recommended Layered Architecture
from decimal import Decimal
from pydantic import BaseModel, Field
class ProductCreate(BaseModel):
name: str
price: Decimal = Field(gt=0)
quantity: int = Field(ge=0)
class ProductRepository:
def __init__(self, db):
self.db = db
def create(self, tenant_id, product):
data = product.model_dump(mode="json")
data["tenant_id"] = tenant_id
doc_ref = self.db.collection("products").document()
doc_ref.set(data)
return {"id": doc_ref.id, **data}
class ProductService:
def __init__(self, repository):
self.repository = repository
def create_product(self, tenant_id, product):
if product.price <= 0:
raise ValueError("Invalid product price")
return self.repository.create(tenant_id, product)
@router.post("/products")
async def create_product(
product: ProductCreate,
context=Depends(get_tenant_context),
service=Depends(get_product_service)
):
return service.create_product(context.tenant_id, product)
Notice that the router doesn't know how Firestore works, the service doesn't know about HTTP status codes, and the repository doesn't decide business rules.
Lesson 11: SOLID Principles Advanced
SOLID is a set of five software design principles that make code maintainable, reusable, and easier to test.
11.1 Single Responsibility Principle (SRP)
A class should have one primary responsibility.
class CustomerManager:
def validate_customer(self, customer): ...
def save_to_firestore(self, customer): ...
def send_welcome_email(self, customer): ...
class CustomerValidator:
def validate(self, customer): ...
class CustomerRepository:
def save(self, customer): ...
class EmailService:
def send_welcome_email(self, customer): ...
Why? Each class has a focused responsibility, making unit testing, maintenance, and component replacement independent.
11.2 Open/Closed Principle (OCP)
Software should be open for extension but closed for modification.
def calculate_discount(customer_type: str, amount: float) -> float:
if customer_type == "regular":
return amount * 0.05
elif customer_type == "premium":
return amount * 0.20
return 0.0
from abc import ABC, abstractmethod
class DiscountStrategy(ABC):
@abstractmethod
def apply(self, amount: float) -> float:
pass
class RegularDiscount(DiscountStrategy):
def apply(self, amount: float) -> float:
return amount * 0.05
class PremiumDiscount(DiscountStrategy):
def apply(self, amount: float) -> float:
return amount * 0.20
def calculate_discount(strategy: DiscountStrategy, amount: float) -> float:
return strategy.apply(amount)
11.3 Liskov Substitution Principle (LSP)
A child class should be usable wherever its parent class is expected without breaking expected behavior. If a PaymentProcessor promises to process payments, every implementation should honor that contract rather than unexpectedly raising NotImplementedError.
11.4 Interface Segregation Principle (ISP)
Avoid forcing a class to implement methods it doesn't need.
class MultiFunctionDevice(ABC):
@abstractmethod
def print_doc(self, doc): pass
@abstractmethod
def scan_doc(self, doc): pass
@abstractmethod
def fax_doc(self, doc): pass
class Printer(ABC):
@abstractmethod
def print_doc(self, doc): pass
class Scanner(ABC):
@abstractmethod
def scan_doc(self, doc): pass
11.5 Dependency Inversion Principle (DIP)
High-level business logic should depend on abstractions rather than concrete implementations.
class OrderService:
def __init__(self):
self.repo = FirestoreOrderRepository() # Tightly coupled!
class OrderRepository(ABC):
@abstractmethod
def save(self, order): pass
class OrderService:
def __init__(self, repo: OrderRepository):
self.repo = repo
Now you can swap Firestore, MongoDB, or an in-memory repository without changing OrderService.
Lesson 12: Dependency Injection Advanced
Dependency Injection (DI) means providing an object with the dependencies it needs rather than creating them internallyβsimilar to Spring's @Autowired.
class CustomerService:
def __init__(self):
self.repo = FirestoreCustomerRepository()
- Tight coupling.
- Difficult to mock in tests or replace implementations.
from fastapi import Depends
def get_customer_repo():
return FirestoreCustomerRepository(db)
def get_customer_service(repo=Depends(get_customer_repo)):
return CustomerService(repo)
@router.get("/customers/{customer_id}")
async def read_customer(
customer_id: str,
service: CustomerService = Depends(get_customer_service)
):
return service.get_customer(customer_id)
| Spring Boot | FastAPI |
|---|---|
@Service | Service class + dependency provider |
@Repository | Repository class |
@Autowired | Depends() |
@Configuration | Dependency provider functions |
Remember: FastAPI DI is not identical to Spring's application contextβyou manage object lifetimes and scopes deliberately.
Lesson 13: Use Dataclasses for Data Objects Important
When a class mainly stores data, you don't need to write constructors, __repr__, and __eq__ manually.
class TenantContext:
def __init__(self, tenant_id: str, user_id: str, role: str):
self.tenant_id = tenant_id
self.user_id = user_id
self.role = role
from dataclasses import dataclass
@dataclass(frozen=True)
class TenantContext:
tenant_id: str
user_id: str
role: str
frozen=True makes the object immutable and prevents accidental reassignment of fields.
When should you use Pydantic instead?
| Dataclass | Pydantic |
|---|---|
| Internal data structures | API request / response models |
| Lightweight objects | Data validation |
| Application domain objects | JSON serialization |
| No automatic input validation | Automatic validation |
For FastAPI request models, Pydantic is generally the better choice.
Lesson 14: Async/Await Best Practices Essential for FastAPI
Python asynchronous programming allows a function to pause while waiting for I/O, letting the event loop execute other tasks.
import time
@app.get("/health")
async def health_check():
time.sleep(2) # Blocks the entire event loop!
return {"status": "ok"}
What's wrong? time.sleep() (or synchronous HTTP/DB calls) blocks the entire event-loop thread. Even though the function is declared async, it stalls all concurrent requests.
import asyncio
@app.get("/health")
async def health_check():
await asyncio.sleep(2) # Non-blocking!
return {"status": "ok"}
httpx.AsyncClient, async DB drivers) inside async def endpoints. If you must call blocking synchronous SDKs (like synchronous Firestore), declare the route with plain def so FastAPI runs it in a threadpool.
Lesson 15: Database & Transaction Handling Essential
Keep database access inside repositories, enforce tenant isolation (tenant_id) on every query, and wrap multi-document updates in atomic transactions or batches so partial failures never leave corrupt state.
@firestore.transactional
def transfer_stock(transaction, src_ref, dst_ref, qty: int):
src_snap = src_ref.get(transaction=transaction)
if src_snap.get("quantity") < qty:
raise ValueError("Insufficient stock")
transaction.update(src_ref, {"quantity": firestore.Increment(-qty)})
transaction.update(dst_ref, {"quantity": firestore.Increment(qty)})
Lesson 16: Security Best Practices Critical
- Never hardcode API keys, secrets, or credentialsβload them from environment variables or a Secret Manager.
- Always validate and sanitize user input with Pydantic schemas.
- Enforce authentication and tenant authorization checks at the dependency/middleware boundary on every protected route.
- Avoid exposing internal stack traces or database errors in API responses.
Lesson 17: Project Structure Essential
Organize FastAPI backends by feature or layer so responsibilities stay clear as the codebase grows:
app/
βββ main.py
βββ core/ # Config, logging, security, dependencies
βββ routers/ # HTTP endpoints (FastAPI APIRouter)
βββ schemas/ # Pydantic request/response models
βββ services/ # Business logic
βββ repositories/ # Firestore / DB access
βββ tests/ # Unit & integration tests
Lesson 18: Testing & Mocking Essential
Because your services depend on repository abstractions via Dependency Injection, you can unit-test business rules with fast in-memory fakes or unittest.mock without hitting Firestore:
from unittest.mock import MagicMock
def test_create_product_calls_repository():
mock_repo = MagicMock()
service = ProductService(repository=mock_repo)
product = ProductCreate(name="Laptop", price=999.99, quantity=5)
service.create_product("tenant_1", product)
mock_repo.create.assert_called_once_with("tenant_1", product)
Ready to Test Your Python Knowledge?
Put these Python concepts into practice with our interactive Python quizzes across Easy, Moderate, and Hard levels.