Mypy Extensions
mypy-extensions provides specific type system extensions for programs checked with the mypy type checker and the mypyc compiler. It acts as a bridge for experimental or mypy-specific typing features that may eventually be standardized in Python's `typing` module or `typing_extensions`, but are supported early by mypy. The library follows mypy's active development and releases are tied to mypy's needs, which typically sees multiple releases per month for the main mypy project.
Warnings
- breaking The main `mypy` type checker, which `mypy-extensions` supports, has removed support for targeting Python 3.8 and now requires `--python-version 3.9` or greater. This means that while `mypy-extensions` 1.1.0 itself requires Python >=3.8, using `mypy` on projects targeting Python 3.8 with these extensions will lead to issues.
- deprecated Mypy's 'Extended Callable types', which provided advanced ways to specify keyword and optional arguments in `Callable` types (and were historically a motivation for such extensions), are now deprecated. Users should migrate to 'callback protocols' instead.
- gotcha Setting `non_interactive = True` in your `mypy.ini` or `setup.cfg` can silently prevent the Visual Studio Code Mypy extension (and potentially other IDE integrations) from displaying type checking errors in the editor, even though `mypy` itself reports them in its raw output.
- gotcha Many types initially provided by `mypy_extensions` (e.g., `TypedDict`, `Literal`, `Protocol`, `TypeGuard`, `Unpack`, `Required`, `NotRequired`, `override`) have since been moved into the standard library `typing` module or `typing_extensions` for broader compatibility across Python versions. Importing from `mypy_extensions` when `typing` or `typing_extensions` suffices can lead to unnecessary dependencies or confusion.
Install
-
pip install mypy-extensions
Imports
- override
from mypy_extensions import override
- Required
from mypy_extensions import Required
- NotRequired
from mypy_extensions import NotRequired
Quickstart
from mypy_extensions import override
from typing import Dict, Any, List
class BaseAnalyzer:
def analyze(self, data: Dict[str, Any]) -> List[str]:
raise NotImplementedError
class SpecificAnalyzer(BaseAnalyzer):
@override
def analyze(self, data: Dict[str, Any]) -> List[str]:
if "items" in data:
return [str(item) for item in data["items"]]
return []
# Example usage for mypy checking
def process_data(analyzer: BaseAnalyzer, input_data: Dict[str, Any]) -> List[str]:
return analyzer.analyze(input_data)
if __name__ == "__main__":
analyzer_instance = SpecificAnalyzer()
results = process_data(analyzer_instance, {"items": [1, "two", 3.0]})
print(f"Analysis results: {results}")
# To type-check this file:
# mypy your_file_name.py