A comprehensive Python code quality checking tool that wraps PyFlakes, pycodestyle, and McCabe to provide unified static analysis with extensible plugin support.
npx @tessl/cli install tessl/pypi-flake8@7.3.0A 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.
pip install flake8import flake8Primary programmatic API:
from flake8.api import legacyCLI interface:
from flake8.main import cli# Basic command line usage (after installation)
# flake8 myfile.py
# flake8 mydirectory/
# flake8 --statistics myproject/from flake8.api import legacy
# Create a style guide
style_guide = legacy.get_style_guide(exclude=['migrations'])
# Check files and get report
report = style_guide.check_files(['myfile.py'])
# Get total error count
print(f"Total errors: {report.total_errors}")
# Get statistics for specific error codes
statistics = report.get_statistics('E501')
for stat in statistics:
print(stat)Flake8's architecture is built around pluggable components:
This modular design allows flake8 to integrate multiple static analysis tools while maintaining extensibility for custom checkers and formatters.
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.
def get_style_guide(**kwargs) -> StyleGuide:
"""
Provision a StyleGuide for programmatic use.
Parameters:
**kwargs: Configuration options for the StyleGuide
Returns:
StyleGuide: Configured instance for checking files
"""
class StyleGuide:
"""Main interface for programmatic file checking."""
def check_files(self, paths: list[str] | None = None) -> Report:
"""Check specified files and return results."""
def excluded(self, filename: str, parent: str | None = None) -> bool:
"""Check if a file is excluded from checking."""
class Report:
"""Results and statistics from a flake8 check run."""
@property
def total_errors(self) -> int:
"""Total number of errors found."""
def get_statistics(self, violation: str) -> list[str]:
"""Get occurrence statistics for a specific violation code."""Command-line entry point and application management for running flake8 as a standalone tool or integrating it into scripts and build systems.
def main(argv: list[str] | None = None) -> int:
"""
Main CLI entry point for flake8.
Parameters:
argv: Command line arguments (defaults to sys.argv[1:])
Returns:
int: Exit code (0 for success, >0 for errors)
"""
class Application:
"""Core application class orchestrating flake8 execution."""
@property
def result_count(self) -> int:
"""Number of errors/warnings found after execution."""Logging configuration and general flake8 setup functionality for controlling output verbosity and log formatting.
def configure_logging(verbosity: int, filename: str | None = None, logformat: str = LOG_FORMAT) -> None:
"""
Configure logging for flake8.
Parameters:
verbosity: How verbose to be (0=no logging, 1=info, 2=debug)
filename: Log file path or "stdout"/"stderr" (None uses stderr)
logformat: Log message format string
"""
__version__: str # Current flake8 version
__version_info__: tuple[int, ...] # Version as tuple of integers
LOG_FORMAT: str # Default log format stringComprehensive exception hierarchy for handling errors during flake8 execution, including plugin loading failures and execution errors.
class Flake8Exception(Exception):
"""Base exception for all flake8 errors."""
class FailedToLoadPlugin(Flake8Exception):
"""Exception raised when a plugin fails to load."""
def __init__(self, plugin_name: str, exception: Exception): ...
class PluginExecutionFailed(Flake8Exception):
"""Exception raised when plugin execution fails."""
def __init__(self, filename: str, plugin_name: str, exception: Exception): ...Base classes and interfaces for creating custom output formatters to control how flake8 violations are displayed and reported.
class BaseFormatter:
"""Base class for all flake8 output formatters."""
def __init__(self, options): ...
def format(self, error: Violation) -> str | None: ...from re import Pattern
from typing import NamedTuple
class Violation(NamedTuple):
"""
Represents a code quality violation found by flake8.
This NamedTuple contains all information about a specific code quality
violation detected during flake8 execution, including location details
and the ability to check for inline ignore comments.
"""
code: str # Error code (e.g., "E501", "W503", "F401")
filename: str # File where violation occurred
line_number: int # Line number of violation (1-based)
column_number: int # Column number of violation (0-based)
text: str # Error message text describing the violation
physical_line: str | None # The actual line content (may be None for stdin)
def is_inline_ignored(self, disable_noqa: bool) -> bool:
"""
Check if violation is ignored by inline # noqa comment.
Parameters:
disable_noqa: Whether --disable-noqa flag was used
Returns:
bool: True if violation should be ignored due to # noqa comment
"""
# Utility Functions
def parse_comma_separated_list(value: str, regexp: Pattern[str] = COMMA_SEPARATED_LIST_RE) -> list[str]:
"""
Parse and normalize a comma-separated list string.
Parameters:
value: String to be parsed and normalized
regexp: Compiled regex pattern for splitting (optional)
Returns:
list[str]: List of parsed, stripped values
"""
# Utility Constants
COMMA_SEPARATED_LIST_RE: Pattern[str] # Regex for splitting comma-separated lists
LOCAL_PLUGIN_LIST_RE: Pattern[str] # Regex for splitting local plugin lists
NORMALIZE_PACKAGE_NAME_RE: Pattern[str] # Regex for normalizing package names