0
# Import Order Checking and Validation
1
2
Main checker functionality for validating import order according to configured style rules, including file loading, AST analysis, and error detection.
3
4
## Capabilities
5
6
### Import Order Checker
7
8
Main class responsible for analyzing Python files and detecting import order violations according to specified style rules.
9
10
```python { .api }
11
class ImportOrderChecker:
12
"""Main checker class for import order validation."""
13
14
visitor_class = ImportVisitor # AST visitor class to use
15
options = None # Configuration options
16
17
def __init__(self, filename, tree):
18
"""
19
Initialize checker with file and AST.
20
21
Args:
22
filename: Path to file being checked
23
tree: Parsed AST or None to load from file
24
"""
25
26
def load_file(self):
27
"""
28
Load and parse file if not already loaded.
29
30
Handles stdin input and regular files, parsing AST if needed.
31
"""
32
33
def check_order(self):
34
"""
35
Check import order and yield errors.
36
37
Yields:
38
Error objects for each import order violation found
39
"""
40
41
def error_is_ignored(self, error):
42
"""
43
Check if error is ignored via # noqa comment.
44
45
Args:
46
error: Error to check
47
48
Returns:
49
True if error should be ignored
50
"""
51
52
def error(self, error):
53
"""
54
Process error for output (override in subclasses).
55
56
Args:
57
error: Error to process
58
59
Returns:
60
Processed error object
61
"""
62
```
63
64
### Configuration and Parsing
65
66
Utilities for parsing configuration options and handling comma-separated lists.
67
68
```python { .api }
69
def parse_comma_separated_list(value):
70
"""
71
Parse comma-separated configuration values.
72
73
Args:
74
value: Comma-separated string (e.g., "name1, name2, name3")
75
76
Returns:
77
Set of stripped, non-empty items
78
79
Example:
80
parse_comma_separated_list("app1, app2 , app3") -> {"app1", "app2", "app3"}
81
"""
82
```
83
84
### Error Detection Constants
85
86
Regular expressions and constants used for error detection and noqa comment parsing.
87
88
```python { .api }
89
DEFAULT_IMPORT_ORDER_STYLE = "cryptography"
90
91
NOQA_INLINE_REGEXP = re.compile(
92
r"# noqa(?:: (?P<codes>([A-Z][0-9]+(?:[,\s]+)?)+))?",
93
re.IGNORECASE,
94
)
95
COMMA_SEPARATED_LIST_RE = re.compile(r"[,\s]")
96
BLANK_LINE_RE = re.compile(r"\s*\n")
97
```
98
99
## Usage Examples
100
101
### Basic Import Order Checking
102
103
```python
104
from flake8_import_order.checker import ImportOrderChecker
105
from flake8_import_order.styles import lookup_entry_point
106
import ast
107
108
# Python code to check
109
code = '''
110
import sys
111
import os
112
from myapp import utils
113
import json
114
'''
115
116
# Set up checker
117
tree = ast.parse(code)
118
checker = ImportOrderChecker('example.py', tree)
119
checker.options = {
120
'application_import_names': ['myapp'],
121
'application_package_names': [],
122
'import_order_style': lookup_entry_point('cryptography')
123
}
124
125
# Check for violations
126
for error in checker.check_order():
127
print(f"Line {error.lineno}: {error.code} - {error.message}")
128
```
129
130
### File-based Checking
131
132
```python
133
from flake8_import_order.checker import ImportOrderChecker
134
from flake8_import_order.styles import lookup_entry_point
135
136
# Check a Python file
137
checker = ImportOrderChecker('mymodule.py', None) # Will load from file
138
checker.options = {
139
'application_import_names': ['myapp', 'myproject'],
140
'application_package_names': ['mycompany'],
141
'import_order_style': lookup_entry_point('google')
142
}
143
144
# Check for violations
145
violations = list(checker.check_order())
146
print(f"Found {len(violations)} import order violations")
147
```
148
149
### Configuration Parsing
150
151
```python
152
from flake8_import_order.checker import parse_comma_separated_list
153
154
# Parse configuration values
155
app_names = parse_comma_separated_list("myapp, tests, utils")
156
print(app_names) # {'myapp', 'tests', 'utils'}
157
158
# Handle empty values
159
empty_names = parse_comma_separated_list("")
160
print(empty_names) # set()
161
```
162
163
### Custom Checker Subclass
164
165
```python
166
from flake8_import_order.checker import ImportOrderChecker
167
168
class CustomChecker(ImportOrderChecker):
169
"""Custom checker with specialized error handling."""
170
171
def error(self, error):
172
"""Custom error formatting."""
173
return {
174
'line': error.lineno,
175
'code': error.code,
176
'message': error.message,
177
'severity': 'warning' if error.code.startswith('I2') else 'error'
178
}
179
180
def check_with_context(self):
181
"""Check with additional context."""
182
errors = []
183
for error in self.check_order():
184
processed_error = self.error(error)
185
errors.append(processed_error)
186
return errors
187
```
188
189
## Error Types and Handling
190
191
The checker detects several types of import order violations:
192
193
### Import Ordering Errors
194
- **I100**: Import statements in wrong order within or between groups
195
- **I666**: Mixed import types in single statement
196
197
### Import Name Ordering Errors
198
- **I101**: Imported names in wrong alphabetical order
199
200
### Import Group Spacing Errors
201
- **I201**: Missing newline between different import groups
202
- **I202**: Additional newline within same import group
203
- **I300**: Incorrect spacing around TYPE_CHECKING blocks
204
205
### NOQA Comment Support
206
207
The checker supports `# noqa` comments to ignore specific errors:
208
209
```python
210
import json
211
import os # noqa: I100 - Ignore wrong order
212
from myapp import utils # noqa - Ignore all errors on this line
213
```