Library

Volume 3 · Python Deep Dive

Notebook
Sign in

Section 14

Error Handling & Testing (pytest fixtures/parametrize, mocking, type hints/mypy, EAFP vs LBYL philosophy)

967 words · about 4 min

14.1 Exception Hierarchy & Custom Exceptions

BaseException
├── SystemExit, KeyboardInterrupt, GeneratorExit   # Don't catch with except Exception
└── Exception                                       # ← catch this, not BaseException
    ├── ArithmeticError, LookupError, AttributeError, TypeError, ValueError
    ├── OSError → FileNotFoundError, ConnectionError, TimeoutError
    ├── RuntimeError → RecursionError, NotImplementedError
    └── ExceptionGroup (3.11+)
class AppError(Exception):
    """Base app exception with an HTTP status code, for a REST API."""
    status_code: int = 500
    def __init__(self, message, details=None):
        super().__init__(message)
        self.details = details or {}

class ValidationError(AppError):
    status_code = 422
    def __init__(self, errors):
        super().__init__("Validation failed", {"errors": errors})

14.2 try/except/else/finally and Chaining

try:
    data = json.loads(raw_data)
except ValueError:
    print("Invalid JSON")        # Only from json.loads
else:
    result = process(data)       # Only runs on success; exceptions here propagate distinctly
finally:
    cleanup()                    # ALWAYS runs

# Explicit chaining — preserves causal context in the traceback
try:
    result = database.query(...)
except ConnectionError as e:
    raise DatabaseError("Failed to fetch user") from e

# ExceptionGroup (3.11+) for multiple simultaneous failures
try:
    validate_data({"age": -5})
except* ValueError as eg:
    for error in eg.exceptions:
        print(error)

14.3 EAFP vs LBYL

# LBYL (Look Before You Leap) — race-condition prone, verbose
if os.path.exists(filepath):
    with open(filepath) as f: data = f.read()

# EAFP (Easier to Ask Forgiveness than Permission) — the Pythonic default
try:
    with open(filepath) as f: data = f.read()
except FileNotFoundError:
    data = default_data

EAFP is preferred in Python partly because it avoids TOCTOU (time-of-check-to-time-of-use) races and because exceptions are cheap when not raised — the “happy path” runs at full speed with no upfront check overhead.

Anti-patterns: bare except: (catches SystemExit/KeyboardInterrupt, breaking Ctrl+C), except Exception: pass (silently swallows real bugs), and overly broad try blocks that make it impossible to tell which of several statements actually failed.

14.4 pytest — Fixtures, Parametrize, Mocking

import pytest
from unittest.mock import Mock, patch

@pytest.fixture
def db_connection():
    conn = create_test_database()
    yield conn                 # provided to the test
    conn.close()                # teardown after the test

@pytest.mark.parametrize("a, b, expected", [
    (2, 3, 5), (-1, 1, 0), (100, -50, 50),
])
def test_add_parametrized(a, b, expected):
    assert add(a, b) == expected

def test_get_user():
    mock_db = Mock()
    mock_db.query.return_value = {"id": 1, "name": "Alice"}
    service = UserService(mock_db)
    assert service.get_user(1)["name"] == "Alice"
    mock_db.query.assert_called_once()

@patch("mymodule.requests.get")
def test_api_call(mock_get):
    mock_get.return_value.json.return_value = {"status": "ok"}
    assert my_api_function() == {"status": "ok"}

Fixture scopes (function/class/module/session) control setup/teardown frequency; fixtures can depend on other fixtures for composable test setup; conftest.py shares fixtures across a whole test directory without imports.

What to mock: external APIs, DB calls, filesystem I/O, network requests, time/randomness. What not to mock: your own pure functions, simple data transformations, or the code actually under test — over-mocking produces tests that pass against a fake reality.

14.5 Type Hints & mypy

from typing import Optional, Callable, TypeVar, Generic, Protocol, Literal

def find(key: str) -> str | None: ...          # 3.10+ union syntax

T = TypeVar("T")
class Stack(Generic[T]):
    def push(self, item: T) -> None: ...
    def pop(self) -> T: ...

def set_mode(mode: Literal["read", "write", "append"]) -> None: ...

def first_new[T](items: list[T]) -> T: ...      # 3.12+ generic syntax, no TypeVar needed

Type hints add zero runtime overhead — they’re purely a static-analysis contract checked by mypy/pyright, not enforced at runtime. greet(42) on def greet(name: str) -> str runs fine at runtime even though mypy flags it; hints improve refactoring safety and documentation but don’t replace runtime validation for untrusted input.

Interview Q&A — Section 14

Q1: What’s the difference between except Exception and bare except:, and why does it matter?

A: Bare except: catches everything, including SystemExit and KeyboardInterrupt, which nearly always should be allowed to propagate (e.g., so Ctrl+C actually stops the program). except Exception: catches ordinary application errors while letting those system-level signals through. Always catch Exception, never bare except: or BaseException unless you have a very specific, deliberate reason.

Q2: Design an exception hierarchy for a REST API.

A: A base AppError(Exception) carrying a status_code class attribute and a details dict, with subclasses like NotFoundError (404), ValidationError (422), AuthenticationError (401), AuthorizationError (403), and RateLimitError (429, carrying retry_after). A single global exception handler catches AppError and formats a consistent JSON error response using exc.status_code and exc.details, so every endpoint gets uniform error semantics without repeating mapping logic.

Q3: Compare pytest fixtures to unittest’s setUp/tearDown.

A: pytest fixtures support arbitrary scopes (function/class/module/session), are dependency-injected by parameter name so tests only request what they need, can depend on other fixtures for composable setup, and use yield for teardown after the test. unittest’s setUp/tearDown are tied to a test class hierarchy, run for every test method regardless of what it actually needs, and compose only through inheritance — less flexible for building layered, reusable test fixtures.

Q4: What are the limitations of type hints, and when do they matter less?

A: They add no runtime enforcement — a type-correct-looking call can still pass an incorrect value at runtime, and passing mypy doesn’t guarantee program correctness. They’re most valuable on public APIs, library code, and long-lived team projects where communication and refactoring safety matter; they matter less for quick throwaway scripts or trivially simple functions. They also get verbose for highly dynamic or metaprogramming-heavy code, and third-party libraries without type stubs limit their usefulness at integration boundaries.