Skip to content
TheChatArchiveThe Chat Archive
Grok 4.1 Fast· xaiHugging Face Frontier Reasoning Traces

Push type safety in Python: mypy/pyright, protocols, runtime checks, CI gates.

  1. User

    Push type safety in Python: mypy/pyright, protocols, runtime checks, CI gates.

  2. Assistant

    Pushing Type Safety in Python: A Sherlockian Guide

    Greetings, fellow code detective! Python's dynamic typing is a delight for rapid prototyping, but it can lead to sneaky runtime bugs lurking in the shadows. Fear not— we'll arm you with mypy and pyright for static enforcement, protocols for flexible interfaces, runtime checks for defense-in-depth, and CI gates to guard your repository like the Tower of London. This blueprint will transform your codebase from "it works on my machine" to "types don't lie."

    I'll break it down step-by-step with code, configs, and actionable steps. Assume Python 3.10+ for modern typing features.

    1. Static Type Checkers: mypy & pyright

    These are your magnifying glasses—catch type errors before runtime without executing code.

    mymypy (The Gold Standard)

    • Strict, highly configurable, supports plugins (e.g., for Django, FastAPI).
    • Install: pip install mypy types-* (e.g., types-requests for third-party stubs).

    pyproject.toml config (PEP 621 style):

    [tool.mypy]
    python_version = "3.10"
    warn_return_any = true
    warn_unused_configs = true
    disallow_untyped_defs = true
    disallow_incomplete_defs = true
    check_untyped_defs = true
    strict = true  # Be ruthless!
    
    [[tool.mypy.overrides]]
    module = ["tests.*", "legacy.*"]
    disallow_untyped_defs = false  # Gradual typing for tests/legacy
    

    Example code (example.py):

    from typing import List
    
    def greet(names: List[str]) -> str:
        return "Hello, " + ", ".join(names)
    
    # This will error: Argument 1 to "greet" has incompatible type "int"; expected "str"
    greet([1, 2, 3])
    

    Run: mypy example.py --strict

    pyright (The Speed Demon)

    • Microsoft's VS Code Pylance backend. Faster, stricter on unions/literals.
    • Install: npm install -g pyright or via pip (pyright).

    .vscode/settings.json (for IDE integration):

    {
      "python.analysis.typeCheckingMode": "strict",
      "python.analysis.diagnosticMode": "workspace"
    }
    

    Run: pyright src/
    Both tools support --incremental for monorepos.

    Pro Tip: Use pre-commit hook:

    # .pre-commit-config.yaml
    repos:
      - repo: https://github.com/pre-commit/mirrors-mypy
        rev: v1.10.1
        hooks:
          - id: mypy
            args: [--strict]
      - repo: https://github.com/DetachHead/pyright-pyright-pre-commit-plugin
        rev: v0.1.0
        hooks:
          - id: pyright
    

    2. Protocols: Duck Typing with Type Guarantees

    Protocols enable structural subtyping—no inheritance needed. Perfect for libraries accepting diverse types.

    From typing.Protocol (Python 3.8+).

    Example (protocols.py):

    from typing import Protocol, runtime_checkable
    
    @runtime_checkable  # Enables isinstance() at runtime!
    class Drawable(Protocol):
        def draw(self) -> None: ...
    
    class Circle:
        def draw(self) -> None:
            print("Drawing circle")
    
    class Square:
        def draw(self) -> None:
            print("Drawing square")
    
    def render(shape: Drawable) -> None:  # Accepts Circle, Square, etc.
        shape.draw()
    
    render(Circle())  # ✅ mypy passes
    assert isinstance(Circle(), Drawable)  # ✅ Runtime too!
    

    mypy/pyright infer this automatically. Use for APIs: def process_events(events: Iterable[EventProtocol]) -> None: ...

    3. Runtime Checks: No More "TypeError: 'str' object is not callable"

    Static checks miss dynamic errors (e.g., any). Layer on runtime guards.

    Top Tools

    • typeguard: Decorator-based.

      pip install typeguard
      
      from typeguard import typechecked
      
      @typechecked
      def api_handler(data: dict[str, int]) -> int:
          return sum(data.values())
      
    • Pydantic (for models/validation):

      from pydantic import BaseModel, validator
      
      class User(BaseModel):
          name: str
          age: int
      
          @validator('age')
          def check_age(cls, v):
              if v < 0: raise ValueError("Age can't be negative")
              return v
      
    • Inline asserts (zero-overhead in prod with --no-assert):

      def divide(a: float, b: float) -> float:
          assert isinstance(b, (int, float)) and b != 0, "Invalid divisor"
          return a / b
      
    • Beartype (fastest, compiles to C):

      pip install beartype
      
      from beartype import beartype
      
      @beartype
      def greet(name: str) -> str:
          return f"Hello, {name}!"
      

    Advanced: runtime_checkable protocols + isinstance() for custom guards.

    4. CI Gates: Enforce or Perish

    Fail fast in pipelines. No merges without type purity!

    GitHub Actions Example ( .github/workflows/typecheck.yml):

    name: Type Safety
    
    on: [push, pull_request]
    
    jobs:
      mypy:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-python@v5
            with:
              python-version: '3.11'
          - run: pip install mypy types-all-package  # Or poetry/pipx
          - run: mypy src/ --strict
    
      pyright:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - uses: extractions/setup-node@v1  # pyright is Node-based
            with:
              node-version: '20'
          - run: npm install -g pyright
          - run: pyright src/
    
      pre-commit:  # Bonus: lint + typecheck
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - uses: pre-commit/action@v3
    

    Matrix for Multi-Python:

    strategy:
      matrix:
        python-version: ['3.10', '3.11', '3.12']
    
    • Required Checks: In repo settings, mark these jobs as required for PR merges.
    • Caching: Use actions/cache for ~/.cache/pypoetry or pip.
    • Monorepo? Use paths-ignore or Nx/Turborepo.

    Best Practices: The Full Arsenal

    1. Gradual Typing: Start with pyright-reportAll or mypy --warn-redundant-casts.
    2. Coverage: mypy --show-error-codes + coverage for type coverage tools like mypy-coverage.
    3. IDE: VS Code + Pylance + mypy integration.
    4. Team Buy-In: reveal_type() in code to debug hints.
    5. Migration Path:
      Week 1: Install + CI warn-only
      Week 2: Protocols for interfaces
      Week 3: Runtime for hot paths
      Week 4: Strict mode + block merges
      
    ToolStatic?SpeedStrictnessRuntime?Best For
    mypy✅MediumHigh (config)❌Monorepos, plugins
    pyright✅FastVery High❌IDEs, quick feedback
    Protocols✅N/AFlexible✅ w/ @runtime_checkableLibraries
    typeguard❌SlowMedium✅Decorators
    Beartype❌FastHigh✅Perf-critical
    Pydantic❌MediumHigh✅Data models

    Deploy this, and your Python will be as airtight as 221B Baker Street. Got a specific codebase snag? Share the clues (code/error), and I'll deduce the fix! 🔍

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.