mypy

mypy is a static type checker for Python that helps detect errors before runtime by analyzing type annotations in code. It enables developers to gradually add typing to existing Python code and verify type correctness without executing the program.

Type Checking Process

  • Static Analysis: Examines code structure and type annotations
  • Type Inference: Deduces types when not explicitly annotated
  • Compatibility Verification: Ensures type-safe operations
  • Error Reporting: Identifies type inconsistencies and potential bugs

Key Features

Type Checking Capabilities

  • Gradual Typing: Allows incremental addition of type annotations
  • Generic Types: Supports parameterized types like List[int]
  • Union Types: Handles multiple possible types with Union[str, int]
  • Type Aliases: Enables creation of named type definitions
  • Protocol Support: Implements structural subtyping for duck typing
  • TypedDict: Offers type-checked dictionaries with specific key types
  • Stubs: Provides type information for libraries without annotations

Pros

  • Error Prevention: Catches type errors before runtime
  • Performance: Faster than running tests for type verification
  • Documentation: Type annotations serve as live documentation
  • IDE Support: Enables better code completion and analysis

Cons

  • False Positives: Can flag code that works correctly at runtime
  • Learning Curve: Type system complexities can be challenging
  • Execution Overhead: Can slow down development workflows
  • Dynamic Features: Struggles with highly dynamic Python patterns

Example Usage

Basic command line usage:

# Install with uv
uv pip install mypy

# Check a single file
mypy example.py

# Check multiple files or directories
mypy src/ tests/

# Enable stricter checking
mypy --strict example.py

Learn More

Last updated on

Please submit corrections and feedback...