0
# Command Line Tools
1
2
Collection of command-line utilities provided by mypy for type checking, stub generation, stub testing, daemon mode, and Python-to-C compilation. These tools form the core interface for mypy's functionality.
3
4
## Capabilities
5
6
### Main Type Checker (mypy)
7
8
The primary static type checker command that analyzes Python code for type errors.
9
10
```python { .api }
11
# Console entry point: mypy.__main__:console_entry
12
# Usage: mypy [options] files/directories
13
```
14
15
#### Common Usage Patterns
16
17
```bash
18
# Basic type checking
19
mypy myfile.py
20
mypy src/
21
22
# Strict mode checking
23
mypy --strict myfile.py
24
25
# Check with specific Python version
26
mypy --python-version 3.11 src/
27
28
# Show error codes
29
mypy --show-error-codes myfile.py
30
31
# Generate coverage report
32
mypy --html-report mypy-report src/
33
34
# Configuration via file
35
mypy src/ # Uses mypy.ini or pyproject.toml
36
```
37
38
#### Key Options
39
40
- `--strict`: Enable all strict mode flags
41
- `--python-version X.Y`: Target Python version
42
- `--platform PLATFORM`: Target platform (linux, win32, darwin)
43
- `--show-error-codes`: Display error codes with messages
44
- `--ignore-missing-imports`: Ignore errors from missing imports
45
- `--follow-imports MODE`: How to handle imports (normal, silent, skip, error)
46
- `--disallow-untyped-defs`: Require type annotations for all functions
47
- `--warn-unused-ignores`: Warn about unused `# type: ignore` comments
48
- `--html-report DIR`: Generate HTML coverage report
49
- `--junit-xml FILE`: Generate JUnit XML test results
50
51
### Stub Generator (stubgen)
52
53
Generates Python stub files (.pyi) from Python modules for type checking.
54
55
```python { .api }
56
# Console entry point: mypy.stubgen:main
57
# Usage: stubgen [options] modules/packages
58
```
59
60
#### Usage Examples
61
62
```bash
63
# Generate stubs for a module
64
stubgen mymodule
65
66
# Generate stubs for multiple modules
67
stubgen module1 module2 package1
68
69
# Generate stubs with output directory
70
stubgen -o stubs/ mymodule
71
72
# Generate stubs for packages with submodules
73
stubgen -p mypackage
74
75
# Include private definitions
76
stubgen --include-private mymodule
77
78
# Generate stubs from installed packages
79
stubgen -m requests numpy
80
```
81
82
#### Key Options
83
84
- `-o DIR`: Output directory for generated stubs
85
- `-p PACKAGE`: Generate stubs for package and subpackages
86
- `-m MODULE`: Generate stubs for installed module
87
- `--include-private`: Include private definitions in stubs
88
- `--export-less`: Don't export names imported from other modules
89
- `--ignore-errors`: Continue despite import errors
90
- `--no-import`: Don't import modules, analyze source only
91
- `--parse-only`: Parse AST without semantic analysis
92
93
### Stub Tester (stubtest)
94
95
Tests stub files for accuracy against the runtime modules they describe.
96
97
```python { .api }
98
# Console entry point: mypy.stubtest:main
99
# Usage: stubtest [options] modules
100
```
101
102
#### Usage Examples
103
104
```bash
105
# Test stubs against runtime module
106
stubtest mymodule
107
108
# Test multiple modules
109
stubtest module1 module2
110
111
# Test with custom stub search path
112
stubtest --mypy-config-file mypy.ini mymodule
113
114
# Allow missing stubs for some items
115
stubtest --allowlist stubtest-allowlist.txt mymodule
116
117
# Generate allowlist of differences
118
stubtest --generate-allowlist mymodule > allowlist.txt
119
```
120
121
#### Key Options
122
123
- `--mypy-config-file FILE`: Use specific mypy configuration
124
- `--allowlist FILE`: File listing acceptable differences
125
- `--generate-allowlist`: Generate allowlist for current differences
126
- `--ignore-missing-stub`: Don't error on missing stub files
127
- `--ignore-positional-only`: Allow positional-only differences
128
- `--concise`: Show fewer details in error messages
129
130
### Daemon Client (dmypy)
131
132
Client for mypy daemon mode, providing faster incremental type checking.
133
134
```python { .api }
135
# Console entry point: mypy.dmypy.client:console_entry
136
# Usage: dmypy [command] [options]
137
```
138
139
#### Daemon Commands
140
141
```bash
142
# Start daemon
143
dmypy daemon
144
145
# Check files using daemon
146
dmypy check myfile.py
147
dmypy check src/
148
149
# Get daemon status
150
dmypy status
151
152
# Stop daemon
153
dmypy stop
154
155
# Restart daemon
156
dmypy restart
157
158
# Kill daemon (force)
159
dmypy kill
160
```
161
162
#### Usage Examples
163
164
```bash
165
# Start daemon with specific options
166
dmypy daemon --log-file daemon.log
167
168
# Incremental checking (much faster)
169
dmypy check --follow-imports=error src/
170
171
# Check with custom configuration
172
dmypy check --config-file mypy.ini src/
173
174
# Verbose output
175
dmypy check --verbose myfile.py
176
177
# Use specific daemon
178
dmypy --status-file custom.status check myfile.py
179
```
180
181
#### Key Options
182
183
- `--status-file FILE`: Custom daemon status file location
184
- `--timeout SECONDS`: Timeout for daemon operations
185
- `--log-file FILE`: Daemon log file location
186
- `--verbose`: Enable verbose output
187
- Standard mypy options apply to `check` command
188
189
### Python-to-C Compiler (mypyc)
190
191
Compiles Python modules with type annotations to efficient C extensions.
192
193
```python { .api }
194
# Console entry point: mypyc.__main__:main
195
# Usage: mypyc [options] files/modules
196
```
197
198
#### Usage Examples
199
200
```bash
201
# Compile a module
202
mypyc mymodule.py
203
204
# Compile multiple modules
205
mypyc module1.py module2.py
206
207
# Compile with optimizations
208
mypyc --opt-level 3 mymodule.py
209
210
# Multi-file compilation
211
mypyc --multi-file package/
212
213
# Debug compilation
214
mypyc --debug-level 2 mymodule.py
215
216
# Show generated C code
217
mypyc --show-c mymodule.py
218
```
219
220
#### Key Options
221
222
- `--opt-level LEVEL`: Optimization level (0-3)
223
- `--debug-level LEVEL`: Debug information level (0-3)
224
- `--multi-file`: Generate multiple C files
225
- `--show-c`: Display generated C code
226
- `--verbose`: Enable verbose compilation output
227
- `--separate`: Compile modules separately
228
- `--no-compile`: Generate C code without compiling
229
230
## Integration Examples
231
232
### Continuous Integration
233
234
```yaml
235
# GitHub Actions example
236
- name: Type check with mypy
237
run: |
238
mypy --strict --show-error-codes src/
239
240
- name: Generate and test stubs
241
run: |
242
stubgen -o stubs/ src/
243
stubtest --mypy-config-file mypy.ini src/
244
```
245
246
### Development Workflow
247
248
```bash
249
#!/bin/bash
250
# development type checking script
251
252
echo "Starting mypy daemon..."
253
dmypy daemon --log-file .mypy-daemon.log
254
255
echo "Type checking project..."
256
dmypy check --follow-imports=error src/
257
258
if [ $? -eq 0 ]; then
259
echo "Type checking passed!"
260
261
echo "Generating stubs..."
262
stubgen -o typestubs/ -p myproject
263
264
echo "Testing stubs..."
265
stubtest --allowlist stubtest.allowlist myproject
266
267
if [ $? -eq 0 ]; then
268
echo "All checks passed!"
269
else
270
echo "Stub tests failed!"
271
exit 1
272
fi
273
else
274
echo "Type checking failed!"
275
exit 1
276
fi
277
278
echo "Stopping daemon..."
279
dmypy stop
280
```
281
282
### Build System Integration
283
284
```python
285
# setup.py with mypyc integration
286
from setuptools import setup
287
from mypyc.build import mypycify
288
289
ext_modules = mypycify([
290
"mypackage/core.py",
291
"mypackage/utils.py",
292
], opt_level="3")
293
294
setup(
295
name="mypackage",
296
ext_modules=ext_modules,
297
# ... other setup parameters
298
)
299
```
300
301
### Editor Integration
302
303
```python
304
# Example editor plugin integration
305
import subprocess
306
from typing import List, Tuple
307
308
def run_mypy(files: List[str]) -> Tuple[bool, str]:
309
"""Run mypy on files and return success status and output."""
310
try:
311
result = subprocess.run(
312
['mypy', '--show-error-codes'] + files,
313
capture_output=True,
314
text=True,
315
timeout=30
316
)
317
318
return result.returncode == 0, result.stdout + result.stderr
319
320
except subprocess.TimeoutExpired:
321
return False, "Mypy timed out"
322
except FileNotFoundError:
323
return False, "Mypy not found - please install mypy"
324
325
def run_stubgen(module: str, output_dir: str) -> bool:
326
"""Generate stubs for module."""
327
try:
328
result = subprocess.run(
329
['stubgen', '-o', output_dir, module],
330
capture_output=True,
331
timeout=30
332
)
333
return result.returncode == 0
334
except (subprocess.TimeoutExpired, FileNotFoundError):
335
return False
336
337
# Usage in editor
338
success, output = run_mypy(['myfile.py'])
339
if not success:
340
# Show errors in editor
341
display_errors(output)
342
```
343
344
## Configuration Files
345
346
### mypy.ini Configuration
347
348
```ini
349
[mypy]
350
python_version = 3.11
351
strict_mode = true
352
show_error_codes = true
353
warn_unused_ignores = true
354
warn_redundant_casts = true
355
356
[mypy-tests.*]
357
ignore_errors = true
358
359
[mypy-thirdparty.*]
360
ignore_missing_imports = true
361
```
362
363
### pyproject.toml Configuration
364
365
```toml
366
[tool.mypy]
367
python_version = "3.11"
368
strict_mode = true
369
show_error_codes = true
370
warn_unused_ignores = true
371
warn_redundant_casts = true
372
373
[[tool.mypy.overrides]]
374
module = "tests.*"
375
ignore_errors = true
376
377
[[tool.mypy.overrides]]
378
module = "thirdparty.*"
379
ignore_missing_imports = true
380
```
381
382
## Performance Tips
383
384
### Daemon Mode Benefits
385
386
- **First run**: Same speed as regular mypy
387
- **Subsequent runs**: 10-50x faster for large codebases
388
- **Best for**: Development environments with frequent checking
389
390
### Incremental Checking
391
392
```bash
393
# Enable incremental mode for faster repeated checks
394
mypy --incremental src/
395
396
# Use cache directory
397
mypy --cache-dir .mypy_cache src/
398
```
399
400
### Stub Generation Optimization
401
402
```bash
403
# Generate stubs for commonly used libraries once
404
stubgen -m requests numpy pandas -o stubs/
405
406
# Use generated stubs in mypy configuration
407
# mypy.ini: [mypy] | mypy_path = stubs/
408
```