0
# Flake8
1
2
A comprehensive Python code quality checking tool that serves as a unified wrapper around multiple static analysis tools including PyFlakes (for logical errors), pycodestyle (for PEP 8 style violations), and McCabe (for cyclomatic complexity analysis). Flake8 provides a single command-line interface that runs all these tools simultaneously and presents their findings in a consolidated report format.
3
4
## Package Information
5
6
- **Package Name**: flake8
7
- **Language**: Python
8
- **Installation**: `pip install flake8`
9
- **Python Requirements**: >=3.9
10
11
## Core Imports
12
13
```python
14
import flake8
15
```
16
17
Primary programmatic API:
18
19
```python
20
from flake8.api import legacy
21
```
22
23
CLI interface:
24
25
```python
26
from flake8.main import cli
27
```
28
29
## Basic Usage
30
31
### Command Line Usage
32
33
```python
34
# Basic command line usage (after installation)
35
# flake8 myfile.py
36
# flake8 mydirectory/
37
# flake8 --statistics myproject/
38
```
39
40
### Programmatic Usage
41
42
```python
43
from flake8.api import legacy
44
45
# Create a style guide
46
style_guide = legacy.get_style_guide(exclude=['migrations'])
47
48
# Check files and get report
49
report = style_guide.check_files(['myfile.py'])
50
51
# Get total error count
52
print(f"Total errors: {report.total_errors}")
53
54
# Get statistics for specific error codes
55
statistics = report.get_statistics('E501')
56
for stat in statistics:
57
print(stat)
58
```
59
60
## Architecture
61
62
Flake8's architecture is built around pluggable components:
63
64
- **Application**: Main orchestration class managing the entire execution flow
65
- **StyleGuide**: Configuration and rule management for code checking
66
- **Checker Manager**: Coordinates running multiple checker plugins across files
67
- **Formatters**: Output formatting and reporting plugins
68
- **Plugin System**: Entry point-based system for extending functionality
69
70
This modular design allows flake8 to integrate multiple static analysis tools while maintaining extensibility for custom checkers and formatters.
71
72
## Capabilities
73
74
### Programmatic API
75
76
The primary stable public API for integrating flake8 into other tools and applications. Provides programmatic access to flake8's code checking functionality with customizable configuration.
77
78
```python { .api }
79
def get_style_guide(**kwargs) -> StyleGuide:
80
"""
81
Provision a StyleGuide for programmatic use.
82
83
Parameters:
84
**kwargs: Configuration options for the StyleGuide
85
86
Returns:
87
StyleGuide: Configured instance for checking files
88
"""
89
90
class StyleGuide:
91
"""Main interface for programmatic file checking."""
92
93
def check_files(self, paths: list[str] | None = None) -> Report:
94
"""Check specified files and return results."""
95
96
def excluded(self, filename: str, parent: str | None = None) -> bool:
97
"""Check if a file is excluded from checking."""
98
99
class Report:
100
"""Results and statistics from a flake8 check run."""
101
102
@property
103
def total_errors(self) -> int:
104
"""Total number of errors found."""
105
106
def get_statistics(self, violation: str) -> list[str]:
107
"""Get occurrence statistics for a specific violation code."""
108
```
109
110
[Programmatic API](./programmatic-api.md)
111
112
### Command Line Interface
113
114
Command-line entry point and application management for running flake8 as a standalone tool or integrating it into scripts and build systems.
115
116
```python { .api }
117
def main(argv: list[str] | None = None) -> int:
118
"""
119
Main CLI entry point for flake8.
120
121
Parameters:
122
argv: Command line arguments (defaults to sys.argv[1:])
123
124
Returns:
125
int: Exit code (0 for success, >0 for errors)
126
"""
127
128
class Application:
129
"""Core application class orchestrating flake8 execution."""
130
131
@property
132
def result_count(self) -> int:
133
"""Number of errors/warnings found after execution."""
134
```
135
136
[Command Line Interface](./cli.md)
137
138
### Configuration and Logging
139
140
Logging configuration and general flake8 setup functionality for controlling output verbosity and log formatting.
141
142
```python { .api }
143
def configure_logging(verbosity: int, filename: str | None = None, logformat: str = LOG_FORMAT) -> None:
144
"""
145
Configure logging for flake8.
146
147
Parameters:
148
verbosity: How verbose to be (0=no logging, 1=info, 2=debug)
149
filename: Log file path or "stdout"/"stderr" (None uses stderr)
150
logformat: Log message format string
151
"""
152
153
__version__: str # Current flake8 version
154
__version_info__: tuple[int, ...] # Version as tuple of integers
155
LOG_FORMAT: str # Default log format string
156
```
157
158
[Configuration and Logging](./config-logging.md)
159
160
### Exception Handling
161
162
Comprehensive exception hierarchy for handling errors during flake8 execution, including plugin loading failures and execution errors.
163
164
```python { .api }
165
class Flake8Exception(Exception):
166
"""Base exception for all flake8 errors."""
167
168
class FailedToLoadPlugin(Flake8Exception):
169
"""Exception raised when a plugin fails to load."""
170
171
def __init__(self, plugin_name: str, exception: Exception): ...
172
173
class PluginExecutionFailed(Flake8Exception):
174
"""Exception raised when plugin execution fails."""
175
176
def __init__(self, filename: str, plugin_name: str, exception: Exception): ...
177
```
178
179
[Exception Handling](./exceptions.md)
180
181
### Custom Formatting
182
183
Base classes and interfaces for creating custom output formatters to control how flake8 violations are displayed and reported.
184
185
```python { .api }
186
class BaseFormatter:
187
"""Base class for all flake8 output formatters."""
188
189
def __init__(self, options): ...
190
def format(self, error: Violation) -> str | None: ...
191
```
192
193
[Custom Formatting](./formatting.md)
194
195
## Types
196
197
```python { .api }
198
from re import Pattern
199
from typing import NamedTuple
200
201
class Violation(NamedTuple):
202
"""
203
Represents a code quality violation found by flake8.
204
205
This NamedTuple contains all information about a specific code quality
206
violation detected during flake8 execution, including location details
207
and the ability to check for inline ignore comments.
208
"""
209
210
code: str # Error code (e.g., "E501", "W503", "F401")
211
filename: str # File where violation occurred
212
line_number: int # Line number of violation (1-based)
213
column_number: int # Column number of violation (0-based)
214
text: str # Error message text describing the violation
215
physical_line: str | None # The actual line content (may be None for stdin)
216
217
def is_inline_ignored(self, disable_noqa: bool) -> bool:
218
"""
219
Check if violation is ignored by inline # noqa comment.
220
221
Parameters:
222
disable_noqa: Whether --disable-noqa flag was used
223
224
Returns:
225
bool: True if violation should be ignored due to # noqa comment
226
"""
227
228
# Utility Functions
229
230
def parse_comma_separated_list(value: str, regexp: Pattern[str] = COMMA_SEPARATED_LIST_RE) -> list[str]:
231
"""
232
Parse and normalize a comma-separated list string.
233
234
Parameters:
235
value: String to be parsed and normalized
236
regexp: Compiled regex pattern for splitting (optional)
237
238
Returns:
239
list[str]: List of parsed, stripped values
240
"""
241
242
# Utility Constants
243
244
COMMA_SEPARATED_LIST_RE: Pattern[str] # Regex for splitting comma-separated lists
245
LOCAL_PLUGIN_LIST_RE: Pattern[str] # Regex for splitting local plugin lists
246
NORMALIZE_PACKAGE_NAME_RE: Pattern[str] # Regex for normalizing package names
247
```