0
# Code Analysis and Transformation
1
2
Core functionality for analyzing Python code with pyflakes and applying transformations to remove unused imports and variables. These functions form the heart of autoflake's code cleanup capabilities.
3
4
## Capabilities
5
6
### Main Code Processing
7
8
High-level functions that combine analysis and transformation to clean Python source code.
9
10
```python { .api }
11
def fix_code(
12
source: str,
13
additional_imports: Iterable[str] | None = None,
14
expand_star_imports: bool = False,
15
remove_all_unused_imports: bool = False,
16
remove_duplicate_keys: bool = False,
17
remove_unused_variables: bool = False,
18
remove_rhs_for_unused_variables: bool = False,
19
ignore_init_module_imports: bool = False,
20
ignore_pass_statements: bool = False,
21
ignore_pass_after_docstring: bool = False
22
) -> str:
23
"""
24
Returns source code with unused imports and variables removed.
25
26
This is the main processing function that applies all filtering operations
27
to clean up Python source code while preserving structure and functionality.
28
29
Args:
30
source: Python source code to process
31
additional_imports: Iterable of modules to consider as unused imports
32
expand_star_imports: Replace star imports with specific imports
33
remove_all_unused_imports: Remove all unused imports, not just standard library
34
remove_duplicate_keys: Remove duplicate keys in dictionaries/sets
35
remove_unused_variables: Remove unused variable assignments
36
remove_rhs_for_unused_variables: Remove right-hand side of unused variable assignments
37
ignore_init_module_imports: Skip import removal in __init__.py files
38
ignore_pass_statements: Don't remove pass statements
39
ignore_pass_after_docstring: Don't remove pass after docstrings
40
41
Returns:
42
Cleaned source code as string
43
"""
44
```
45
46
```python { .api }
47
def filter_code(
48
source: str,
49
additional_imports: Iterable[str] | None = None,
50
expand_star_imports: bool = False,
51
ignore_init_module_imports: bool = False,
52
remove_all_unused_imports: bool = False,
53
remove_duplicate_keys: bool = False,
54
remove_unused_variables: bool = False,
55
remove_rhs_for_unused_variables: bool = False
56
) -> Iterable[str]:
57
"""
58
Yields lines of code with unused imports and variables removed.
59
60
Lower-level function that yields processed lines. Used internally by fix_code
61
but can be used directly for streaming processing of large files.
62
63
Args:
64
source: Python source code to process
65
additional_imports: Additional modules to remove
66
expand_star_imports: Replace star imports with specific imports
67
ignore_init_module_imports: Skip removal in __init__.py files
68
remove_all_unused_imports: Remove all unused imports
69
remove_duplicate_keys: Remove duplicate dictionary keys
70
remove_unused_variables: Remove unused variables
71
remove_rhs_for_unused_variables: Remove right-hand side of unused variable assignments
72
73
Yields:
74
Processed source code lines
75
"""
76
```
77
78
### Code Analysis
79
80
Functions for analyzing Python source code to identify unused imports, variables, and other cleanup opportunities.
81
82
```python { .api }
83
def check(source: str) -> Iterable[pyflakes.messages.Message]:
84
"""
85
Returns pyflakes messages for the given source code.
86
87
Provides direct access to pyflakes analysis results for custom processing
88
or integration with other tools.
89
90
Args:
91
source: Python source code to analyze
92
93
Returns:
94
Iterator of pyflakes Message objects describing issues found
95
"""
96
```
97
98
### Message Processing Functions
99
100
Functions that extract specific information from pyflakes analysis results.
101
102
```python { .api }
103
def unused_import_line_numbers(
104
messages: Iterable[pyflakes.messages.Message]
105
) -> Iterable[int]:
106
"""
107
Yields line numbers of unused imports from pyflakes messages.
108
109
Args:
110
messages: Pyflakes messages from code analysis
111
112
Yields:
113
Line numbers containing unused imports
114
"""
115
```
116
117
```python { .api }
118
def unused_import_module_name(
119
messages: Iterable[pyflakes.messages.Message]
120
) -> Iterable[tuple[int, str]]:
121
"""
122
Yields line number and module name of unused imports.
123
124
Args:
125
messages: Pyflakes messages from code analysis
126
127
Yields:
128
Tuples of (line_number, module_name) for unused imports
129
"""
130
```
131
132
```python { .api }
133
def star_import_used_line_numbers(
134
messages: Iterable[pyflakes.messages.Message]
135
) -> Iterable[int]:
136
"""
137
Yields line numbers where star imports are used.
138
139
Args:
140
messages: Pyflakes messages from code analysis
141
142
Yields:
143
Line numbers containing star import usage
144
"""
145
```
146
147
```python { .api }
148
def star_import_usage_undefined_name(
149
messages: Iterable[pyflakes.messages.Message]
150
) -> Iterable[tuple[int, str, str]]:
151
"""
152
Yields information about undefined names that might come from star imports.
153
154
Args:
155
messages: Pyflakes messages from code analysis
156
157
Yields:
158
Tuples of (line_number, undefined_name, possible_origin_module)
159
"""
160
```
161
162
```python { .api }
163
def unused_variable_line_numbers(
164
messages: Iterable[pyflakes.messages.Message]
165
) -> Iterable[int]:
166
"""
167
Yields line numbers of unused variables.
168
169
Args:
170
messages: Pyflakes messages from code analysis
171
172
Yields:
173
Line numbers containing unused variable assignments
174
"""
175
```
176
177
```python { .api }
178
def duplicate_key_line_numbers(
179
messages: Iterable[pyflakes.messages.Message],
180
source: str
181
) -> Iterable[int]:
182
"""
183
Yields line numbers of duplicate keys in dictionaries.
184
185
Args:
186
messages: Pyflakes messages from code analysis
187
source: Source code being analyzed
188
189
Yields:
190
Line numbers containing duplicate dictionary keys
191
"""
192
```
193
194
```python { .api }
195
def create_key_to_messages_dict(
196
messages: Iterable[pyflakes.messages.MultiValueRepeatedKeyLiteral]
197
) -> Mapping[Any, Iterable[pyflakes.messages.MultiValueRepeatedKeyLiteral]]:
198
"""
199
Creates mapping from keys to their duplicate key messages.
200
201
Args:
202
messages: Duplicate key messages from pyflakes
203
204
Returns:
205
Dictionary mapping keys to lists of messages
206
"""
207
```
208
209
### Pass Statement Processing
210
211
Functions for handling Python `pass` statements that may become redundant after removing unused code.
212
213
```python { .api }
214
def filter_useless_pass(
215
source: str,
216
ignore_pass_statements: bool = False,
217
ignore_pass_after_docstring: bool = False
218
) -> Iterable[str]:
219
"""
220
Yields code with useless 'pass' statements removed.
221
222
Removes pass statements that are no longer needed after other code
223
has been removed, while preserving structurally necessary pass statements.
224
225
Args:
226
source: Python source code to process
227
ignore_pass_statements: Don't remove any pass statements
228
ignore_pass_after_docstring: Keep pass statements after docstrings
229
230
Yields:
231
Source code lines with useless pass statements removed
232
"""
233
234
```python { .api }
235
def useless_pass_line_numbers(
236
source: str,
237
ignore_pass_after_docstring: bool = False
238
) -> Iterable[int]:
239
"""
240
Yields line numbers of useless pass statements that can be removed.
241
242
Identifies pass statements that serve no structural purpose and can be
243
safely removed without affecting Python syntax or semantics.
244
245
Args:
246
source: Python source code to analyze
247
ignore_pass_after_docstring: Don't consider pass after docstrings as useless
248
249
Yields:
250
Line numbers containing useless pass statements
251
"""
252
```
253
254
### Supporting Classes
255
256
Classes that support the analysis and transformation process.
257
258
```python { .api }
259
class ListReporter:
260
"""
261
Accumulates pyflakes messages in a list for programmatic access.
262
263
Inherits from pyflakes.reporter.Reporter and provides a way to collect
264
all analysis messages for further processing.
265
"""
266
def __init__(self) -> None:
267
"""Initialize the reporter with an empty message list."""
268
269
def flake(self, message: pyflakes.messages.Message) -> None:
270
"""
271
Add a pyflakes message to the accumulated list.
272
273
Args:
274
message: Pyflakes message to store
275
"""
276
```
277
278
```python { .api }
279
class FilterMultilineImport:
280
"""
281
Handles removal of unused imports from multiline import statements.
282
283
This class manages the complex logic needed to properly parse and filter
284
imports that span multiple lines while preserving proper Python syntax.
285
"""
286
def __init__(self, line: str) -> None:
287
"""
288
Initialize with the first line of a multiline import.
289
290
Args:
291
line: First line of the multiline import statement
292
"""
293
294
def __call__(self, line: str) -> FilterMultilineImport | str:
295
"""
296
Process the next line of the multiline import.
297
298
Args:
299
line: Next line to process
300
301
Returns:
302
Either a string (processed line) or self for continued processing
303
"""
304
```
305
306
## Usage Examples
307
308
### Basic Code Cleaning
309
310
```python
311
import autoflake
312
313
# Clean up simple unused imports
314
source = '''
315
import os
316
import sys
317
import unused_module
318
319
def hello():
320
print("Hello")
321
'''
322
323
cleaned = autoflake.fix_code(source, remove_all_unused_imports=True)
324
# Result: Only keeps 'print' and removes unused imports
325
```
326
327
### Custom Analysis
328
329
```python
330
import autoflake
331
332
# Get detailed analysis information
333
messages = list(autoflake.check(source_code))
334
unused_imports = list(autoflake.unused_import_line_numbers(messages))
335
unused_vars = list(autoflake.unused_variable_line_numbers(messages))
336
337
print(f"Unused imports on lines: {unused_imports}")
338
print(f"Unused variables on lines: {unused_vars}")
339
```
340
341
### Advanced Processing
342
343
```python
344
import autoflake
345
346
# Advanced cleanup with all options
347
cleaned = autoflake.fix_code(
348
source_code,
349
remove_all_unused_imports=True,
350
remove_unused_variables=True,
351
remove_duplicate_keys=True,
352
expand_star_imports=True,
353
ignore_pass_after_docstring=True
354
)
355
```