A comprehensive Python code quality checking tool that wraps PyFlakes, pycodestyle, and McCabe to provide unified static analysis with extensible plugin support.
—
The stable public API for integrating flake8 into other tools and applications. This API provides programmatic access to flake8's code checking functionality with full configuration control.
Create a configured StyleGuide instance for checking Python files programmatically.
def get_style_guide(**kwargs) -> StyleGuide:
"""
Provision a StyleGuide for programmatic use.
This is the main entry point for programmatic flake8 usage. Creates and
configures a StyleGuide instance that can be used to check files.
Parameters:
**kwargs: Configuration options that correspond to command-line options:
- exclude: List of patterns to exclude files/directories
- select: List of error codes to check for
- ignore: List of error codes to ignore
- max_line_length: Maximum line length (default 79)
- max_complexity: Maximum cyclomatic complexity
- show_source: Show source lines in output
- statistics: Show violation statistics
- count: Show count of violations
- format: Output format string
- output_file: File to write results to
Returns:
StyleGuide: Configured instance ready for checking files
Example:
style_guide = get_style_guide(
exclude=['migrations', '*.pyc'],
ignore=['E203', 'W503'],
max_line_length=88
)
"""Usage example:
from flake8.api import legacy
# Create style guide with custom configuration
style_guide = legacy.get_style_guide(
exclude=['migrations', 'venv', '.git'],
ignore=['E203', 'W503'], # Ignore specific error codes
max_line_length=88,
show_source=True
)
# Check files
report = style_guide.check_files(['myproject/'])
print(f"Found {report.total_errors} violations")Check Python files for code quality violations using a configured StyleGuide.
class StyleGuide:
"""
Main interface for programmatic file checking.
This class provides methods to check files, determine exclusions,
and configure reporting options.
"""
def check_files(self, paths: list[str] | None = None) -> Report:
"""
Run flake8 checks on specified files and return results.
Parameters:
paths: List of file paths or directories to check.
If None, uses paths from command line options.
Returns:
Report: Object containing check results and statistics
Example:
report = style_guide.check_files(['app.py', 'tests/'])
"""
def excluded(self, filename: str, parent: str | None = None) -> bool:
"""
Determine if a file should be excluded from checking.
Parameters:
filename: Path to the file to check
parent: Parent directory path (optional)
Returns:
bool: True if file should be excluded, False otherwise
Example:
if not style_guide.excluded('myfile.py'):
# File will be checked
"""
def input_file(self, filename: str, lines=None, expected=None, line_offset=0) -> Report:
"""
Check a single file and return results.
Parameters:
filename: Path to file to check
lines: Ignored (legacy parameter)
expected: Ignored (legacy parameter)
line_offset: Ignored (legacy parameter)
Returns:
Report: Check results for the single file
"""
def init_report(self, reporter=None) -> None:
"""
Initialize a custom formatter for output.
Parameters:
reporter: Custom BaseFormatter subclass for output formatting
If None, uses default formatter
"""
@property
def options(self):
"""Access to parsed configuration options."""
@property
def paths(self) -> list[str]:
"""List of file paths configured for checking."""Usage example:
# Check specific files
report = style_guide.check_files(['app.py', 'utils.py'])
# Check if file would be excluded
if style_guide.excluded('migrations/0001_initial.py'):
print("File is excluded from checking")
# Check single file
single_report = style_guide.input_file('test.py')Access check results and violation statistics through the Report interface.
class Report:
"""
Results and statistics from a flake8 check run.
Provides access to error counts, violation statistics, and detailed
results from checking operations.
"""
@property
def total_errors(self) -> int:
"""
Total number of errors and warnings found.
Returns:
int: Count of all violations found during checking
"""
def get_statistics(self, violation: str) -> list[str]:
"""
Get occurrence statistics for a specific violation code.
Returns formatted statistics showing count, error code, and message
for each occurrence of the specified violation type.
Parameters:
violation: Error code to get statistics for (e.g., 'E501', 'W503')
Returns:
list[str]: List of formatted statistics strings in format:
"{count} {error_code} {message}"
Example:
stats = report.get_statistics('E501')
# Returns: ['3 E501 line too long (82 > 79 characters)']
"""Usage example:
# Get total error count
total = report.total_errors
print(f"Total violations: {total}")
# Get statistics for specific error codes
line_length_stats = report.get_statistics('E501')
for stat in line_length_stats:
print(f"Line length violation: {stat}")
# Get all import-related violations
import_stats = report.get_statistics('E401')
for stat in import_stats:
print(f"Import issue: {stat}")from flake8.api import legacy
def check_code_quality(project_path, config=None):
"""Check code quality for a Python project."""
# Configure style guide
config = config or {}
style_guide = legacy.get_style_guide(
exclude=config.get('exclude', ['migrations', '.git', '__pycache__']),
ignore=config.get('ignore', []),
max_line_length=config.get('max_line_length', 88),
show_source=True,
statistics=True
)
# Run checks
report = style_guide.check_files([project_path])
# Report results
print(f"Code quality check complete!")
print(f"Total violations found: {report.total_errors}")
# Show statistics for common violations
common_errors = ['E501', 'E302', 'E305', 'W291', 'F401']
for error_code in common_errors:
stats = report.get_statistics(error_code)
if stats:
print(f"\n{error_code} violations:")
for stat in stats:
print(f" {stat}")
return report.total_errors == 0
# Usage
if __name__ == "__main__":
is_clean = check_code_quality("myproject/")
exit(0 if is_clean else 1)Install with Tessl CLI
npx tessl i tessl/pypi-flake8