0
# Autoflake
1
2
Autoflake removes unused imports and unused variables from Python code as reported by pyflakes. It provides both a command-line tool for batch processing and a comprehensive Python API for programmatic integration into linting workflows, automated refactoring tools, and code cleanup pipelines.
3
4
## Package Information
5
6
- **Package Name**: autoflake
7
- **Language**: Python
8
- **Installation**: `pip install autoflake`
9
- **Entry Point**: `autoflake` command (CLI) or `import autoflake` (library)
10
11
## Core Imports
12
13
```python
14
import autoflake
15
```
16
17
Common imports for programmatic usage:
18
19
```python
20
from autoflake import fix_code, fix_file, check
21
```
22
23
## Basic Usage
24
25
### CLI Usage
26
27
```bash
28
# Fix a single file in place
29
autoflake --in-place --remove-unused-variables example.py
30
31
# Remove all unused imports and variables
32
autoflake --in-place --remove-all-unused-imports --remove-unused-variables example.py
33
34
# Process multiple files recursively
35
autoflake --in-place --recursive --remove-unused-variables src/
36
```
37
38
### Library Usage
39
40
```python
41
import autoflake
42
43
# Basic code cleanup
44
source_code = '''
45
import os
46
import sys
47
import unused_module
48
49
def hello():
50
unused_var = "not used"
51
print("Hello World")
52
'''
53
54
# Fix the code
55
cleaned_code = autoflake.fix_code(
56
source_code,
57
remove_unused_variables=True,
58
remove_all_unused_imports=True
59
)
60
61
print(cleaned_code)
62
```
63
64
## Architecture
65
66
Autoflake's architecture centers around several key components:
67
68
- **Analysis Engine**: Uses pyflakes to identify unused imports and variables
69
- **Code Transformation**: Parses and filters Python source code while preserving structure
70
- **Configuration System**: Supports pyproject.toml and setup.cfg configuration files
71
- **File Processing**: Handles individual files, directories, and batch operations with encoding detection
72
73
The library intelligently handles complex scenarios like multiline imports, star imports, side-effect imports marked with `# noqa`, and standard library detection, making it safe for automated use in CI/CD pipelines.
74
75
## Capabilities
76
77
### Code Analysis and Transformation
78
79
Core functionality for analyzing Python code with pyflakes and applying transformations to remove unused imports and variables while preserving code structure and functionality.
80
81
```python { .api }
82
def fix_code(
83
source: str,
84
additional_imports: Iterable[str] | None = None,
85
expand_star_imports: bool = False,
86
remove_all_unused_imports: bool = False,
87
remove_duplicate_keys: bool = False,
88
remove_unused_variables: bool = False,
89
remove_rhs_for_unused_variables: bool = False,
90
ignore_init_module_imports: bool = False,
91
ignore_pass_statements: bool = False,
92
ignore_pass_after_docstring: bool = False
93
) -> str
94
```
95
96
```python { .api }
97
def filter_code(
98
source: str,
99
additional_imports: Iterable[str] | None = None,
100
expand_star_imports: bool = False,
101
ignore_init_module_imports: bool = False,
102
remove_all_unused_imports: bool = False,
103
remove_duplicate_keys: bool = False,
104
remove_unused_variables: bool = False,
105
remove_rhs_for_unused_variables: bool = False
106
) -> Iterable[str]
107
```
108
109
```python { .api }
110
def check(source: str) -> Iterable[pyflakes.messages.Message]
111
```
112
113
[Code Analysis and Transformation](./code-analysis.md)
114
115
### File Processing and Batch Operations
116
117
Functions for processing individual files and directories with proper encoding detection, pattern matching, and batch operation support for integration into larger workflows.
118
119
```python { .api }
120
def fix_file(
121
filename: str,
122
args: Mapping[str, Any],
123
standard_out: IO[str] | None = None
124
) -> int
125
```
126
127
```python { .api }
128
def find_files(
129
filenames: list[str],
130
recursive: bool,
131
exclude: Iterable[str]
132
) -> Iterable[str]
133
```
134
135
```python { .api }
136
def is_python_file(filename: str) -> bool
137
```
138
139
[File Processing](./file-processing.md)
140
141
### Configuration Management
142
143
Comprehensive configuration system supporting pyproject.toml and setup.cfg files with command-line argument merging for flexible deployment across different project structures.
144
145
```python { .api }
146
def process_pyproject_toml(toml_file_path: str) -> MutableMapping[str, Any] | None
147
```
148
149
```python { .api }
150
def merge_configuration_file(
151
flag_args: MutableMapping[str, Any]
152
) -> tuple[MutableMapping[str, Any], bool]
153
```
154
155
```python { .api }
156
def find_and_process_config(args: Mapping[str, Any]) -> MutableMapping[str, Any] | None
157
```
158
159
[Configuration](./configuration.md)
160
161
### Standard Library and Import Detection
162
163
Functions for detecting and handling Python standard library imports, package names, and import patterns to ensure safe removal while preserving necessary functionality.
164
165
```python { .api }
166
def standard_package_names() -> Iterable[str]
167
```
168
169
```python { .api }
170
def extract_package_name(line: str) -> str | None
171
```
172
173
```python { .api }
174
def multiline_import(line: str, previous_line: str = "") -> bool
175
```
176
177
[Import Detection](./import-detection.md)
178
179
## Types
180
181
```python { .api }
182
class ListReporter:
183
"""Accumulates pyflakes messages in a list for programmatic access."""
184
def __init__(self) -> None: ...
185
def flake(self, message: pyflakes.messages.Message) -> None: ...
186
187
class FilterMultilineImport:
188
"""Handles removal of unused imports from multiline import statements."""
189
def __init__(self, line: str) -> None: ...
190
def __call__(self, line: str) -> FilterMultilineImport | str: ...
191
```
192
193
## Constants
194
195
```python { .api }
196
__version__: str # "2.3.1"
197
SAFE_IMPORTS: frozenset[str] # Standard library imports safe for removal
198
IMPORTS_WITH_SIDE_EFFECTS: set[str] # Known imports with side effects
199
```
200
201
## CLI Entry Point
202
203
```python { .api }
204
def main() -> int
205
```
206
207
Command-line interface entry point with comprehensive argument parsing, configuration file support, and signal handling for robust CLI operation.