🐍

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

  1. Bad practice: How developers commonly write code incorrectly.
  2. Best practice: How we should write it.
  3. Why? Why the recommended approach is better.
  4. Real-world example: Where to use it in production backends.

Learning Roadmap (18 Core Topics)

Lesson 1: Naming Conventions Essential

Python has established naming conventions defined in PEP 8.

1.1 Variable naming

❌ Avoid this
x = "Murugan"
y = 25
z = True

What's wrong?

  • What does x represent?
  • What does y represent?
  • What does z represent?
  • Other developers cannot easily understand the purpose.
βœ… Recommended
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

❌ Avoid this
def GetCustomer(id):
    pass

def addProduct():
    pass
βœ… Recommended
def get_customer(customer_id):
    pass

def add_product(product):
    pass
PythonJava / Kotlin
get_customer()getCustomer()
customer_namecustomerName
CustomerServiceCustomerService

1.3 Class naming

❌ Avoid this
class customer_service:
    pass
βœ… Recommended
class CustomerService:
    pass

Python uses PascalCase for classes.

1.4 Boolean naming

❌ Avoid this
active = True
deleted = False
βœ… Recommended
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.

❌ Avoid this
total_amount = 0

def add_amount(amount):
    global total_amount
    total_amount += amount

What's wrong?

  1. Any function can accidentally modify the global variable.
  2. Functions become dependent on external state.
  3. Unit testing becomes harder.
  4. Concurrent requests can introduce race conditions.
βœ… Recommended
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.

β˜• Java Equivalent
public double addAmount(double current, double amount) {
    return current + amount;
}
Note: Not all global variables are bad. Immutable application configuration and constants (e.g., MAX_RETRY_COUNT = 3) are perfectly reasonable.

Lesson 3: Never Use Mutable Default Arguments Critical

❌ Avoid this – Important!
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.

βœ… Recommended
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']
Remember this rule: Never use mutable objects such as 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.

❌ Avoid this
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.
βœ… Recommended
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
Important: Python type hints do not automatically enforce types at runtime. Use tools such as Pyright or mypy for static type checking.

Lesson 5: Avoid Unnecessary else Statements Essential

❌ Avoid this
def get_discount(customer):
    if customer.is_premium:
        return 20
    else:
        return 5
βœ… Recommended
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.

Practical Guard-Clause Example
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

❌ Avoid this
def divide(a, b):
    try:
        return a / b
    except:
        return None
  • It catches almost every exception (even KeyboardInterrupt or SystemExit).
  • Programming errors (like TypeError) can be hidden.
  • Debugging becomes difficult and useful error information is lost.
βœ… Recommended
def divide(a: float, b: float) -> float:
    try:
        return a / b
    except ZeroDivisionError:
        raise ValueError("Divisor cannot be zero")
πŸš€ FastAPI Example
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

❌ Avoid this
def create_customer(customer):
    print("Creating customer...")
    print(customer)
βœ… Recommended
import logging

logger = logging.getLogger(__name__)

def create_customer(customer):
    logger.info("Creating customer")
    # Business logic
LevelPurpose
DEBUGDetailed debugging information
INFONormal application events
WARNINGUnexpected but recoverable situations
ERROROperation failed
CRITICALSerious 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

❌ Avoid
def create_user(name, metadata={}):
    metadata["name"] = name
    return metadata
βœ… Recommended
def create_user(name, metadata=None):
    if metadata is None:
        metadata = {}
    metadata["name"] = name
    return metadata
Remember: Mutable defaults include 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

❌ Avoid
file = open("data.txt", "w")
file.write("Hello Python")
file.close()  # May not run if an exception occurs!
βœ… Recommended
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.

❌ Bad Architecture
@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

Router HTTP Request / Response
→
Service Business Rules
→
Repository Database Operations
→
Firestore Data Store
βœ… Step 1: Schema
from decimal import Decimal
from pydantic import BaseModel, Field

class ProductCreate(BaseModel):
    name: str
    price: Decimal = Field(gt=0)
    quantity: int = Field(ge=0)
βœ… Step 2: Repository
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}
βœ… Step 3: Service
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)
βœ… Step 4: Router
@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.

❌ Avoid this
class CustomerManager:
    def validate_customer(self, customer): ...
    def save_to_firestore(self, customer): ...
    def send_welcome_email(self, customer): ...
βœ… Recommended
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.

❌ Avoid this
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
βœ… Recommended
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.

❌ Avoid this
class MultiFunctionDevice(ABC):
    @abstractmethod
    def print_doc(self, doc): pass
    @abstractmethod
    def scan_doc(self, doc): pass
    @abstractmethod
    def fax_doc(self, doc): pass
βœ… Recommended
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.

❌ Avoid this
class OrderService:
    def __init__(self):
        self.repo = FirestoreOrderRepository()  # Tightly coupled!
βœ… Recommended
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.

❌ Avoid this
class CustomerService:
    def __init__(self):
        self.repo = FirestoreCustomerRepository()
  • Tight coupling.
  • Difficult to mock in tests or replace implementations.
βœ… Recommended (FastAPI Dependency Injection)
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 BootFastAPI
@ServiceService class + dependency provider
@RepositoryRepository class
@AutowiredDepends()
@ConfigurationDependency 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.

❌ Avoid this
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
βœ… Recommended
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?

DataclassPydantic
Internal data structuresAPI request / response models
Lightweight objectsData validation
Application domain objectsJSON serialization
No automatic input validationAutomatic 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.

❌ Avoid this
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.

βœ… Recommended
import asyncio

@app.get("/health")
async def health_check():
    await asyncio.sleep(2)  # Non-blocking!
    return {"status": "ok"}
Tip for FastAPI: Use async libraries (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.

🐍 Go to Python Quiz ⚑ Start Moderate Quiz