0
# Plugin Integrations
1
2
Flake8 and pylama linter integrations that provide command-line options, configuration parsing, and error formatting for seamless integration with Python linting workflows.
3
4
## Capabilities
5
6
### Flake8 Integration
7
8
Flake8 plugin implementation that integrates import order checking into the flake8 linting framework.
9
10
```python { .api }
11
class Linter(ImportOrderChecker):
12
"""Flake8 linter integration for import order checking."""
13
14
name = "import-order" # Plugin name for flake8
15
version = __version__ # Plugin version from package metadata
16
17
def __init__(self, tree, filename, lines=None):
18
"""
19
Initialize flake8 linter.
20
21
Args:
22
tree: Parsed AST of the file
23
filename: Name of file being checked
24
lines: File lines (optional, will be loaded from file if None)
25
"""
26
27
@classmethod
28
def add_options(cls, parser):
29
"""
30
Add flake8 command-line options.
31
32
Adds options for:
33
- --application-import-names: Application import names
34
- --application-package-names: Application package names
35
- --import-order-style: Import ordering style to use
36
37
Args:
38
parser: Flake8 option parser
39
"""
40
41
@classmethod
42
def parse_options(cls, options):
43
"""
44
Parse and store flake8 options.
45
46
Args:
47
options: Parsed options from flake8
48
"""
49
50
@staticmethod
51
def list_available_styles():
52
"""
53
List available import order styles.
54
55
Returns:
56
Sorted list of available style names
57
"""
58
59
def run(self):
60
"""
61
Run import order checking for flake8.
62
63
Yields:
64
Flake8-format error tuples (line, col, message, type)
65
"""
66
67
def error(self, error):
68
"""
69
Format error for flake8 output.
70
71
Args:
72
error: Import order error
73
74
Returns:
75
Flake8-format error tuple
76
"""
77
```
78
79
### Pylama Integration
80
81
Pylama linter implementation that integrates import order checking into the pylama linting framework.
82
83
```python { .api }
84
class Linter(ImportOrderChecker, BaseLinter):
85
"""Pylama linter integration for import order checking."""
86
87
name = "import-order" # Linter name for pylama
88
version = __version__ # Linter version from package metadata
89
90
def __init__(self):
91
"""Initialize pylama linter."""
92
93
def allow(self, path):
94
"""
95
Check if file should be linted.
96
97
Args:
98
path: File path to check
99
100
Returns:
101
True if file should be linted (ends with .py)
102
"""
103
104
def run(self, path, **meta):
105
"""
106
Run import order checking for pylama.
107
108
Args:
109
path: File path to check
110
**meta: Metadata including configuration options
111
112
Yields:
113
Pylama-format error dictionaries
114
"""
115
116
def error(self, error):
117
"""
118
Format error for pylama output.
119
120
Args:
121
error: Import order error
122
123
Returns:
124
Pylama-format error dictionary with keys:
125
- lnum: Line number
126
- col: Column number (always 0)
127
- text: Error message
128
- type: Error code
129
"""
130
```
131
132
### Option Registration Utilities
133
134
Utility functions for registering options with different versions of flake8.
135
136
```python { .api }
137
def register_opt(parser, *args, **kwargs):
138
"""
139
Register option with flake8 parser, handling version differences.
140
141
Supports both flake8 2.x and 3.x option registration formats.
142
143
Args:
144
parser: Flake8 option parser
145
*args: Option arguments (e.g., '--option-name')
146
**kwargs: Option keyword arguments including:
147
- parse_from_config: Whether to parse from config files
148
- comma_separated_list: Whether to treat as comma-separated
149
- default: Default value
150
- help: Help text
151
- type: Option type
152
"""
153
```
154
155
## Usage Examples
156
157
### Flake8 Configuration
158
159
Configure flake8-import-order in `setup.cfg` or `tox.ini`:
160
161
```ini
162
[flake8]
163
# Enable import order checking
164
select = E,W,F,I
165
166
# Configure import order style
167
import-order-style = cryptography
168
169
# Specify application import names
170
application-import-names = myapp,tests,utils
171
172
# Specify application package names (for appnexus/edited styles)
173
application-package-names = mycompany
174
175
# Set maximum line length
176
max-line-length = 88
177
```
178
179
### Command Line Usage
180
181
```bash
182
# Run flake8 with import order checking
183
flake8 --import-order-style=google --application-import-names=myapp myfile.py
184
185
# List available styles
186
flake8 --help | grep import-order-style
187
```
188
189
### Pylama Configuration
190
191
Configure in `pylama.ini` or `setup.cfg`:
192
193
```ini
194
[pylama]
195
# Enable import order linter
196
linters = pyflakes,mccabe,import_order
197
198
# Configure import order style
199
import_order_style = google
200
201
# Specify application imports
202
application_import_names = myapp,tests
203
```
204
205
### Programmatic Usage with Flake8
206
207
```python
208
from flake8_import_order.flake8_linter import Linter
209
import ast
210
211
# Set up linter with options
212
code = '''
213
import json
214
import os
215
from myapp import utils
216
'''
217
218
tree = ast.parse(code)
219
linter = Linter(tree, 'example.py')
220
221
# Configure options
222
class Options:
223
application_import_names = ['myapp']
224
application_package_names = []
225
import_order_style = 'cryptography'
226
227
Linter.parse_options(Options())
228
229
# Run linting
230
for error in linter.run():
231
line, col, message, error_type = error
232
print(f"Line {line}: {message}")
233
```
234
235
### Programmatic Usage with Pylama
236
237
```python
238
from flake8_import_order.pylama_linter import Linter
239
240
# Create linter instance
241
linter = Linter()
242
243
# Check file
244
errors = list(linter.run('myfile.py',
245
import_order_style='google',
246
application_import_names=['myapp']))
247
248
for error in errors:
249
print(f"Line {error['lnum']}: {error['type']} - {error['text']}")
250
```
251
252
### Custom Integration
253
254
```python
255
from flake8_import_order.flake8_linter import Linter as FlakeLinter
256
import ast
257
258
class CustomLinter(FlakeLinter):
259
"""Custom linter with additional features."""
260
261
def run(self):
262
"""Enhanced run method with custom processing."""
263
errors = list(super().run())
264
265
# Add custom processing
266
if errors:
267
print(f"Found {len(errors)} import order issues")
268
269
return iter(errors)
270
271
def error(self, error):
272
"""Custom error formatting."""
273
line, col, message, error_type = super().error(error)
274
275
# Add custom prefix
276
custom_message = f"[IMPORT-ORDER] {message}"
277
278
return (line, col, custom_message, error_type)
279
```
280
281
## Integration Points
282
283
### Entry Points Registration
284
285
The plugin registers itself with flake8 and pylama through setuptools entry points:
286
287
```python
288
# In setup.cfg:
289
[options.entry_points]
290
flake8.extension =
291
I = flake8_import_order.flake8_linter:Linter
292
293
pylama.linter =
294
import_order = flake8_import_order.pylama_linter:Linter
295
```
296
297
### Configuration Options
298
299
Both integrations support the following configuration options:
300
301
- **application-import-names**: Comma-separated list of application import names
302
- **application-package-names**: Comma-separated list of application package names
303
- **import-order-style**: Style name to use (default: 'cryptography')
304
305
### Error Format Compatibility
306
307
The integrations format errors to match their respective framework conventions:
308
309
**Flake8 Format**: `(line_number, column_number, "ERROR_CODE message", error_class)`
310
311
**Pylama Format**: `{"lnum": line_number, "col": column_number, "text": "message", "type": "ERROR_CODE"}`
312
313
### Version Compatibility
314
315
The flake8 integration handles both flake8 2.x and 3.x versions through the `register_opt` utility function that adapts to different option registration APIs.