Skip to content
AstralSurge Learnings
Follow LinkedIn X RSS

Modern Python Best Practices: Idiomatic, Performant, and Maintainable Code

Writing Pythonic code requires moving beyond basic syntax to understand memory management, static typing, structured concurrency, and modern development workflows.

1. Static Typing and Self-Documenting Signatures

Modern Python (3.10+) heavily leverages type hints. This improves code clarity and enables automated static analysis with tools like mypy.

from dataclasses import dataclass
from typing import Optional

@dataclass(frozen=True)
class CustomerRecord:
    customer_id: int
    name: str
    balance: float
    email: Optional[str] = None

def calculate_discount(customer: CustomerRecord, discount_rate: float) -> float:
    """Calculates discounted balance ensuring non-negative limits."""
    if not 0.0 <= discount_rate <= 1.0:
        raise ValueError("Discount rate must be between 0.0 and 1.0")
    return round(customer.balance * (1.0 - discount_rate), 2)

2. Resource Management with Context Managers

Never manually invoke .close() on file descriptors or network connections. Utilize with blocks or contextlib to guarantee clean cleanup even if exceptions occur.

from pathlib import Path

file_path = Path("reports") / "quarterly.csv"
file_path.parent.mkdir(parents=True, exist_ok=True)

# Safe reading with context manager
with file_path.open(mode="r", encoding="utf-8") as file:
    for line in file:
        print(line.strip())

3. Memory Efficiency: Generators vs. List Comprehensions

When streaming datasets of millions of records, list comprehensions allocate all items into memory simultaneously. Generator expressions calculate items lazily on demand.

# List comprehension: All 1,000,000 items loaded into memory
squares_list = [x * x for x in range(1_000_000)]

# Generator expression: O(1) memory usage, elements yielded on iteration
squares_gen = (x * x for x in range(1_000_000))
print(next(squares_gen)) # 0
print(next(squares_gen)) # 1

4. Proper Identity Comparison: "is" vs "=="

  • == checks for equality of values (calls __eq__).
  • is checks for identity in memory (id(a) == id(b)). Always use is None or is not None.

5. Modern Tooling and Packaging Ecosystem

Move beyond legacy setup.py. Modern Python standards utilize pyproject.toml managed by high-speed tools like uv or Poetry, alongside Ruff for ultra-fast linting and code formatting.

0 Comments