Mypy - Professional Static Type Checking
Mypy is a static type checker for Python that finds bugs without running code. This skill provides comprehensive guidance for professional mypy integration and usage.
Quick Start
Installation and Basic Usage
# Install mypy
python3 -m pip install mypy
# Check a file
mypy program.py
# Check with strict mode
mypy --strict program.py
Basic Type Annotations
def greeting(name: str) -> str:
return 'Hello ' + name
# Type checking catches errors
greeting(3) # Error: Argument has incompatible type "int"; expected "str"
Configuration
Mypy supports multiple configuration formats (discovery order):
mypy.ini.mypy.inipyproject.toml(with[tool.mypy]section)setup.cfg(with[mypy]section)
Essential Configuration Options
# mypy.ini
[mypy]
python_version = 3.11
warn_return_any = True
warn_unused_configs = True
disallow_untyped_defs = True
# Per-module configuration
[mypy-module_name.*]
ignore_missing_imports = True
See references/config_file.md for complete configuration reference.
Core Workflows
Adding Types to Existing Code
- Start with
--check-untyped-defsfor gradual typing - Use
# type: ignorecomments sparingly for temporary exceptions - Add type annotations incrementally, module by module
- Enable stricter checks progressively
See references/existing_code.md for migration strategies.
Resolving Type Errors
When mypy reports errors:
- Check the error code (e.g.,
[attr-defined]) - Consult error code documentation:
references/error_code_list.md- Default errorsreferences/error_code_list2.md- Optional checks
- Use type narrowing techniques when needed
- Consider
reveal_type()for debugging type inference
See references/common_issues.md for troubleshooting.
Working with Advanced Types
Generics: references/generics.md
- TypeVar, Generic classes, bounded type variables
- Variance (covariant, contravariant, invariant)
Protocols: references/protocols.md
- Structural subtyping, runtime checkable protocols
- Protocol composition
TypedDict: references/typed_dict.md
- Required vs optional keys, inheritance
- Total vs non-total TypedDicts
Literal Types: references/literal_types.md
- String/int/bool/Enum literals
- Exhaustiveness checking
See references/kinds_of_types.md for type system overview.
Command Line Reference
# Strict mode (recommended for new projects)
mypy --strict module.py
# Check specific paths
mypy src/ tests/
# Generate HTML coverage report
mypy --html-report ./mypy-report src/
# Use mypy daemon for faster checking
dmypy run -- src/
# Generate stubs from existing code
stubgen -p mypackage -o stubs/
See references/command_line.md for all CLI options.
CI/CD Integration
GitHub Actions Example
- name: Type check with mypy
run: |
pip install mypy
mypy --install-types --non-interactive
mypy src/
Pre-commit Hook
# .pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.19.1
hooks:
- id: mypy
additional_dependencies: [types-all]
Reference Documentation
The references/ directory contains complete mypy 1.19.1 documentation:
Getting Started
getting_started.md- Installation, basic conceptscheat_sheet_py3.md- Quick reference guide
Type System
builtin_types.md- Python built-in typestype_inference_and_annotations.md- Annotations guidekinds_of_types.md- Type system overviewclass_basics.md- Class typing fundamentalsprotocols.md- Structural subtypinggenerics.md- Generic types and TypeVarstyped_dict.md- TypedDict patternsliteral_types.md- Literal types and Enumsfinal_attrs.md- Final declarationsmore_types.md- Additional type patternstype_narrowing.md- Type narrowing techniquesduck_type_compatibility.md- Duck typing rules
Configuration & Running
config_file.md- Complete configuration referencecommand_line.md- CLI options and flagsrunning_mypy.md- Running mypy guideinline_config.md- Inline type commentsmypy_daemon.md- Daemon mode for speedinstalled_packages.md- Package type stubs
Advanced Topics
stubs.md- Stub files guidestubgen.md- Automatic stub generationstubtest.md- Stub testing toolextending_mypy.md- Plugins and extensionsmetaclasses.md- Metaclass typingruntime_troubles.md- Runtime annotation issuesdynamic_typing.md- Dynamic typing patterns
Troubleshooting
error_codes.md- Error code systemerror_code_list.md- Default error codeserror_code_list2.md- Optional error codescommon_issues.md- Solutions to common issuesfaq.md- Frequently asked questions
Project Info
additional_features.md- Advanced featuressupported_python_features.md- Python version supportexisting_code.md- Migration strategieschangelog.md- Version history
Updating Documentation
The scripts/ directory contains tools to refresh documentation from mypy.readthedocs.io:
# Discover all documentation pages
python scripts/discover_pages.py > mypy_pages.txt
# Bulk scrape and clean documentation
python scripts/scrape_docs.py
# Clean individual markdown files
python scripts/clean_markdown.py input.md output.md
These scripts use cloudscraper for Cloudflare bypass and automatically clean navigation/footer content.
Best Practices
- Start gradually - Use
--check-untyped-defsinitially - Configure per-module - Different strictness for different parts of codebase
- Use error codes - Specific
# type: ignore[code]instead of blanket ignores - Leverage inference - Let mypy infer types when obvious
- Run in CI - Catch type errors before merge
- Update regularly - Stay current with mypy releases for better type checking
Common Patterns
Optional Values
from typing import Optional
def find_user(id: int) -> Optional[User]:
# May return None
return user_db.get(id)
Union Types
from typing import Union
def process(value: Union[int, str]) -> str:
if isinstance(value, int):
return str(value)
return value
Generic Functions
from typing import TypeVar, Sequence
T = TypeVar('T')
def first(seq: Sequence[T]) -> T:
return seq[0]
Protocol (Structural Typing)
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...
def render(obj: Drawable) -> None:
obj.draw() # Any object with draw() works
Version Information
This skill is based on mypy 1.19.1 (stable) documentation. Use the scraping scripts to update to newer versions as they are released.
Converted and distributed by TomeVault — claim your Tome and manage your conversions.