0
# Configuration
1
2
Runtime configuration capabilities for customizing mypy integration behavior through conftest.py and global variables. Provides programmatic control over mypy execution, error formatting, and test naming.
3
4
## Capabilities
5
6
### Global Configuration Variables
7
8
Direct access to plugin configuration through global variables that can be modified at runtime.
9
10
```python { .api }
11
# Global mypy command line arguments
12
mypy_argv: List[str]
13
"""
14
Global list of mypy command line arguments.
15
16
Automatically populated from pytest command line options and can be
17
extended programmatically in conftest.py for additional mypy configuration.
18
19
Example modifications:
20
- mypy_argv.append('--check-untyped-defs')
21
- mypy_argv.extend(['--strict', '--warn-redundant-casts'])
22
"""
23
24
# Test name formatting function
25
test_name_formatter: Callable[[MypyFileItem], str]
26
"""
27
Function used to format test names in pytest reports.
28
29
Default implementation shows "[mypy] relative/path/to/file.py".
30
Can be replaced with custom formatter for different naming schemes.
31
32
Parameters:
33
- item: MypyFileItem being formatted
34
35
Returns:
36
Formatted test name string for display in reports
37
"""
38
39
# File error formatting function
40
file_error_formatter: Callable[[MypyItem, MypyResults, List[str]], str]
41
"""
42
Function used to format mypy error messages for display.
43
44
Default implementation respects --mypy-report-style setting.
45
Can be replaced with custom formatter for specialized error display.
46
47
Parameters:
48
- item: MypyItem that encountered errors
49
- results: Complete MypyResults from execution
50
- lines: List of error lines for this item
51
52
Returns:
53
Formatted error message string for display
54
"""
55
```
56
57
### Default Formatters
58
59
Built-in formatter functions that can be used or replaced.
60
61
```python { .api }
62
def default_test_name_formatter(*, item: MypyFileItem) -> str:
63
"""
64
Default formatter for mypy test names.
65
66
Creates test names in the format "[mypy] relative/path/to/file.py"
67
using the file path relative to the pytest invocation directory.
68
69
Parameters:
70
- item: MypyFileItem to generate name for
71
72
Returns:
73
Formatted test name with [mypy] prefix and relative path
74
"""
75
76
def default_file_error_formatter(
77
item: MypyItem,
78
results: MypyResults,
79
lines: List[str]
80
) -> str:
81
"""
82
Default formatter for mypy error messages.
83
84
Formats error lines according to --mypy-report-style setting:
85
- 'mypy': Preserves original mypy output format
86
- 'no-path': Strips path prefixes for cleaner display
87
88
Parameters:
89
- item: MypyItem that encountered the errors
90
- results: Complete mypy execution results
91
- lines: Error lines to format
92
93
Returns:
94
Formatted error message string
95
"""
96
```
97
98
### Plugin Access Pattern
99
100
Standard pattern for accessing and configuring the mypy plugin.
101
102
```python { .api }
103
def pytest_configure(config: pytest.Config) -> None:
104
"""
105
Standard hook for configuring the mypy plugin.
106
107
The plugin module can be imported directly to access
108
global configuration variables and functions.
109
110
Parameters:
111
- config: Pytest configuration object
112
"""
113
import pytest_mypy
114
115
# Direct access to global configuration variables
116
pytest_mypy.mypy_argv.extend(['--strict', '--check-untyped-defs'])
117
pytest_mypy.test_name_formatter = custom_formatter
118
pytest_mypy.file_error_formatter = custom_error_formatter
119
```
120
121
### Configuration Constants
122
123
Plugin constants that define behavior and can be referenced for customization.
124
125
```python { .api }
126
item_marker: str = "mypy"
127
"""Marker name applied to all mypy test items for filtering."""
128
129
nodeid_name: str = "mypy"
130
"""Base node ID name used for mypy test items."""
131
132
terminal_summary_title: str = "mypy"
133
"""Title used in pytest terminal summary section."""
134
```
135
136
## Configuration Examples
137
138
### Basic Mypy Arguments Extension
139
```python
140
# conftest.py
141
def pytest_configure(config):
142
"""Add additional mypy checking options."""
143
import pytest_mypy
144
145
# Enable strict type checking
146
pytest_mypy.mypy_argv.extend([
147
'--strict',
148
'--check-untyped-defs',
149
'--warn-redundant-casts',
150
'--warn-unused-ignores'
151
])
152
```
153
154
### Custom Test Name Formatting
155
```python
156
# conftest.py
157
def pytest_configure(config):
158
"""Customize mypy test names for better readability."""
159
import pytest_mypy
160
161
def custom_test_name(*, item):
162
"""Show just filename instead of full path."""
163
return f"[mypy] {item.path.name}"
164
165
pytest_mypy.test_name_formatter = custom_test_name
166
```
167
168
### Advanced Error Formatting
169
```python
170
# conftest.py
171
def pytest_configure(config):
172
"""Customize mypy error display format."""
173
import pytest_mypy
174
175
def detailed_error_formatter(item, results, lines):
176
"""Add context and statistics to error messages."""
177
error_count = len(lines)
178
header = f"Found {error_count} type issues in {item.path.name}:"
179
180
formatted_lines = []
181
for line in lines:
182
# Add severity highlighting
183
if "error:" in line:
184
formatted_lines.append(f"❌ {line}")
185
elif "warning:" in line:
186
formatted_lines.append(f"⚠️ {line}")
187
else:
188
formatted_lines.append(f"ℹ️ {line}")
189
190
return header + "\n" + "\n".join(formatted_lines)
191
192
pytest_mypy.file_error_formatter = detailed_error_formatter
193
```
194
195
### Conditional Configuration
196
```python
197
# conftest.py
198
import os
199
200
def pytest_configure(config):
201
"""Configure mypy based on environment."""
202
import pytest_mypy
203
204
# Strict checking in CI environment
205
if os.getenv('CI'):
206
pytest_mypy.mypy_argv.extend([
207
'--strict',
208
'--warn-unreachable',
209
'--disallow-any-generics'
210
])
211
else:
212
# More lenient for local development
213
pytest_mypy.mypy_argv.extend([
214
'--ignore-missing-imports',
215
'--allow-redefinition'
216
])
217
```
218
219
### Integration with Other Tools
220
```python
221
# conftest.py
222
def pytest_configure(config):
223
"""Integrate mypy configuration with project settings."""
224
import pytest_mypy
225
226
# Use project-specific mypy configuration
227
project_mypy_config = config.rootpath / "tools" / "mypy.ini"
228
if project_mypy_config.exists():
229
pytest_mypy.mypy_argv.append(f"--config-file={project_mypy_config}")
230
231
# Custom exclusions based on pytest collection
232
if hasattr(config.option, 'ignore_paths'):
233
for ignore_path in config.option.ignore_paths:
234
pytest_mypy.mypy_argv.append(f"--exclude={ignore_path}")
235
```
236
237
### Error Handling Customization
238
```python
239
# conftest.py
240
def pytest_configure(config):
241
"""Add custom error handling and reporting."""
242
import pytest_mypy
243
244
# Store original error formatter
245
original_formatter = pytest_mypy.file_error_formatter
246
247
def logging_error_formatter(item, results, lines):
248
"""Log errors to external system before displaying."""
249
# Log to external monitoring system
250
import logging
251
logger = logging.getLogger('mypy_errors')
252
logger.error(f"Type errors in {item.path}: {len(lines)} issues")
253
254
# Use original formatting for display
255
return original_formatter(item, results, lines)
256
257
pytest_mypy.file_error_formatter = logging_error_formatter
258
```