Optional static typing for Python with powerful type system and gradual typing support
npx @tessl/cli install tessl/pypi-mypy@1.17.00
# Mypy
1
2
A static type checker for Python that uses type hints to analyze code without running it. Mypy enables gradual typing, allowing developers to add type annotations incrementally to existing codebases while providing powerful static analysis capabilities including type inference, generics, union types, and structural subtyping.
3
4
## Package Information
5
6
- **Package Name**: mypy
7
- **Language**: Python
8
- **Installation**: `pip install mypy`
9
- **Python Version**: >=3.9
10
11
## Core Imports
12
13
```python
14
import mypy
15
```
16
17
For programmatic usage:
18
19
```python
20
from mypy import api
21
```
22
23
For advanced build integration:
24
25
```python
26
from mypy.build import build, BuildSource, BuildResult
27
from mypy.options import Options
28
```
29
30
## Basic Usage
31
32
### Command Line Usage
33
34
```python
35
# Basic type checking
36
import subprocess
37
result = subprocess.run(['mypy', 'myfile.py'], capture_output=True, text=True)
38
print(result.stdout)
39
```
40
41
### Programmatic API Usage
42
43
```python
44
from mypy import api
45
46
# Type check files programmatically
47
result = api.run(['myfile.py'])
48
stdout, stderr, exit_code = result
49
50
if exit_code == 0:
51
print("Type checking passed!")
52
else:
53
print("Type errors found:")
54
print(stderr)
55
```
56
57
### Advanced Build Integration
58
59
```python
60
from mypy.build import build, BuildSource
61
from mypy.options import Options
62
63
# Configure options
64
options = Options()
65
options.strict_mode = True
66
options.python_version = (3, 11)
67
68
# Define sources to analyze
69
sources = [BuildSource("myfile.py", module=None, text=None)]
70
71
# Perform analysis
72
result = build(sources, options)
73
74
# Check for errors
75
if result.errors:
76
for error in result.errors:
77
print(f"{error.file}:{error.line}: {error.message}")
78
else:
79
print("No type errors found!")
80
```
81
82
## Architecture
83
84
Mypy's architecture consists of several key components:
85
86
- **Parser**: Converts Python source code into mypy's AST representation
87
- **Semantic Analyzer**: Builds symbol tables and resolves names and imports
88
- **Type Checker**: Performs static type analysis using the type system
89
- **Type System**: Comprehensive type representations including generics, unions, and protocols
90
- **Plugin System**: Extensible architecture for custom type checking logic
91
- **Build System**: Manages incremental analysis and dependency tracking
92
93
The type checker supports Python's full type system including type variables, generic types, callable types, union types, literal types, TypedDict, Protocol classes, and advanced features like ParamSpec and TypeVarTuple.
94
95
## Capabilities
96
97
### Command Line Tools
98
99
Collection of command-line utilities for type checking, stub generation, stub testing, daemon mode, and Python-to-C compilation.
100
101
```python { .api }
102
# Entry points available as console commands:
103
# mypy - Main type checker
104
# stubgen - Generate stub files (.pyi)
105
# stubtest - Test stub files for accuracy
106
# dmypy - Daemon mode for faster checking
107
# mypyc - Compile Python to C extensions
108
```
109
110
[Command Line Tools](./command-line-tools.md)
111
112
### Programmatic API
113
114
Simple API functions for integrating mypy into Python applications, providing programmatic access to type checking functionality.
115
116
```python { .api }
117
def run(args: list[str]) -> tuple[str, str, int]:
118
"""
119
Run mypy programmatically with command line arguments.
120
121
Parameters:
122
- args: Command line arguments as list of strings
123
124
Returns:
125
- tuple: (stdout, stderr, exit_code)
126
"""
127
128
def run_dmypy(args: list[str]) -> tuple[str, str, int]:
129
"""
130
Run dmypy daemon client programmatically.
131
132
Parameters:
133
- args: Command line arguments as list of strings
134
135
Returns:
136
- tuple: (stdout, stderr, exit_code)
137
138
Note: Not thread-safe, modifies sys.stdout/stderr
139
"""
140
```
141
142
[Programmatic API](./programmatic-api.md)
143
144
### Build System Integration
145
146
Advanced APIs for custom build systems and development tools that need fine-grained control over the type checking process.
147
148
```python { .api }
149
def build(sources, options, alt_lib_path=None, flush_errors=None,
150
fscache=None, stdout=None, stderr=None, extra_plugins=None) -> BuildResult:
151
"""
152
Main function to analyze a program programmatically.
153
154
Parameters:
155
- sources: List of BuildSource objects to analyze
156
- options: Options object with configuration settings
157
- alt_lib_path: Alternative library path (optional)
158
- flush_errors: Error flushing callback (optional)
159
- fscache: File system cache (optional)
160
- stdout: Output stream (optional)
161
- stderr: Error stream (optional)
162
- extra_plugins: Additional plugins (optional)
163
164
Returns:
165
- BuildResult: Analysis results with errors and file information
166
"""
167
168
class BuildSource:
169
"""Represents a source file or module to be analyzed."""
170
171
class BuildResult:
172
"""Contains the results of type checking analysis."""
173
174
class Options:
175
"""Configuration container for all mypy settings."""
176
```
177
178
[Build System Integration](./build-system.md)
179
180
### Type System
181
182
Comprehensive type representations used by mypy's static analysis engine, including all Python type system features.
183
184
```python { .api }
185
class Type:
186
"""Abstract base class for all type representations."""
187
188
class Instance:
189
"""Represents instances of classes and built-in types."""
190
191
class CallableType:
192
"""Represents function and method types with call signatures."""
193
194
class UnionType:
195
"""Represents union types (X | Y or Union[X, Y])."""
196
197
class TypeVarType:
198
"""Represents type variables for generic programming."""
199
200
class LiteralType:
201
"""Represents literal value types (Literal['value'])."""
202
```
203
204
[Type System](./type-system.md)
205
206
### Error System
207
208
Error codes, error handling classes, and error reporting functionality for comprehensive type checking diagnostics.
209
210
```python { .api }
211
class ErrorCode:
212
"""Represents specific error types with descriptions and categories."""
213
214
class Errors:
215
"""Collects and formats error messages during type checking."""
216
217
class CompileError(Exception):
218
"""Exception raised when type checking fails."""
219
220
# Key error codes
221
ATTR_DEFINED: ErrorCode
222
NAME_DEFINED: ErrorCode
223
CALL_ARG: ErrorCode
224
TYPE_ARG: ErrorCode
225
RETURN_VALUE: ErrorCode
226
```
227
228
[Error System](./error-system.md)
229
230
### AST and Node System
231
232
Abstract syntax tree representation and node types used internally by mypy for code analysis.
233
234
```python { .api }
235
class Node:
236
"""Abstract base class for all AST nodes."""
237
238
class MypyFile:
239
"""Represents an entire source file."""
240
241
class ClassDef:
242
"""Represents class definitions."""
243
244
class FuncDef:
245
"""Represents function and method definitions."""
246
247
class Expression:
248
"""Base class for expression nodes."""
249
250
class Statement:
251
"""Base class for statement nodes."""
252
```
253
254
[AST and Node System](./ast-nodes.md)
255
256
### Plugin System
257
258
Extensible plugin architecture for customizing type checking behavior and adding support for specific libraries or frameworks.
259
260
```python { .api }
261
class Plugin:
262
"""Base class for mypy plugins."""
263
264
class CommonPluginApi:
265
"""Common API available to plugin callbacks."""
266
267
class SemanticAnalyzerPluginInterface:
268
"""API available during semantic analysis phase."""
269
270
class CheckerPluginInterface:
271
"""API available during type checking phase."""
272
```
273
274
[Plugin System](./plugin-system.md)
275
276
### Stub Generation and Testing
277
278
Tools for generating and validating Python stub files (.pyi) for type checking without runtime dependencies.
279
280
```python { .api }
281
# Available through stubgen command
282
def main(): # stubgen.main
283
"""Main entry point for stub generation."""
284
285
# Available through stubtest command
286
def main(): # stubtest.main
287
"""Main entry point for stub validation."""
288
```
289
290
[Stub Tools](./stub-tools.md)
291
292
### Daemon Mode
293
294
High-performance daemon mode for faster incremental type checking in development environments.
295
296
```python { .api }
297
# Available through dmypy command and run_dmypy() API
298
# Provides faster incremental checking for large codebases
299
```
300
301
[Daemon Mode](./daemon-mode.md)
302
303
### MypyC Compiler
304
305
Python-to-C compiler that generates efficient C extensions from Python code with type annotations.
306
307
```python { .api }
308
# Available through mypyc command
309
def main(): # mypyc.__main__.main
310
"""Main compiler entry point."""
311
312
def mypycify(paths, **kwargs): # mypyc.build.mypycify
313
"""Compile Python modules to C extensions."""
314
```
315
316
[MypyC Compiler](./mypyc-compiler.md)
317
318
## Types
319
320
### Core Configuration Types
321
322
```python { .api }
323
class Options:
324
"""
325
Configuration container for all mypy settings.
326
327
Attributes:
328
- python_version: tuple[int, int] - Target Python version
329
- platform: str - Target platform
330
- strict_mode: bool - Enable all strict mode flags
331
- show_error_codes: bool - Show error codes in output
332
- ignore_missing_imports: bool - Ignore missing import errors
333
- disallow_untyped_defs: bool - Disallow untyped function definitions
334
- disallow_any_generics: bool - Disallow generic types without type parameters
335
- warn_redundant_casts: bool - Warn about redundant casts
336
- warn_unused_ignores: bool - Warn about unused # type: ignore comments
337
"""
338
339
BuildType = int # Constants: STANDARD, MODULE, PROGRAM_TEXT
340
```
341
342
### Build System Types
343
344
```python { .api }
345
class BuildSource:
346
"""
347
Represents a source file or module to be analyzed.
348
349
Attributes:
350
- path: str - File path (or None for modules)
351
- module: str - Module name (or None for files)
352
- text: str - Source text (or None to read from file)
353
"""
354
355
class BuildResult:
356
"""
357
Contains the results of type checking analysis.
358
359
Attributes:
360
- errors: list[str] - List of error messages
361
- files: dict - Information about analyzed files
362
- types: dict - Type information mapping
363
- manager: BuildManager | None - Build manager instance
364
"""
365
366
class BuildManager:
367
"""
368
Build manager that coordinates parsing, import processing,
369
semantic analysis and type checking.
370
371
Attributes:
372
- data_dir: str - Mypy data directory
373
- search_paths: SearchPaths - Module search paths
374
- modules: dict[str, MypyFile] - Loaded modules
375
- options: Options - Build options
376
"""
377
378
class FileSystemCache:
379
"""
380
File system cache for improved performance during mypy operations.
381
382
Methods:
383
- flush(): Clear all cached data
384
- set_package_root(package_root: list[str]): Set package root directories
385
"""
386
387
class SearchPaths:
388
"""
389
Configuration for module search paths used during import resolution.
390
391
Attributes:
392
- python_path: tuple[str, ...] - User code locations
393
- mypy_path: tuple[str, ...] - MYPYPATH directories
394
- package_path: tuple[str, ...] - Site-packages directories
395
- typeshed_path: tuple[str, ...] - Typeshed locations
396
"""
397
```