Removes unused imports and unused variables from Python code
npx @tessl/cli install tessl/pypi-autoflake@2.3.0Autoflake 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.
pip install autoflakeautoflake command (CLI) or import autoflake (library)import autoflakeCommon imports for programmatic usage:
from autoflake import fix_code, fix_file, check# Fix a single file in place
autoflake --in-place --remove-unused-variables example.py
# Remove all unused imports and variables
autoflake --in-place --remove-all-unused-imports --remove-unused-variables example.py
# Process multiple files recursively
autoflake --in-place --recursive --remove-unused-variables src/import autoflake
# Basic code cleanup
source_code = '''
import os
import sys
import unused_module
def hello():
unused_var = "not used"
print("Hello World")
'''
# Fix the code
cleaned_code = autoflake.fix_code(
source_code,
remove_unused_variables=True,
remove_all_unused_imports=True
)
print(cleaned_code)Autoflake's architecture centers around several key components:
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.
Core functionality for analyzing Python code with pyflakes and applying transformations to remove unused imports and variables while preserving code structure and functionality.
def fix_code(
source: str,
additional_imports: Iterable[str] | None = None,
expand_star_imports: bool = False,
remove_all_unused_imports: bool = False,
remove_duplicate_keys: bool = False,
remove_unused_variables: bool = False,
remove_rhs_for_unused_variables: bool = False,
ignore_init_module_imports: bool = False,
ignore_pass_statements: bool = False,
ignore_pass_after_docstring: bool = False
) -> strdef filter_code(
source: str,
additional_imports: Iterable[str] | None = None,
expand_star_imports: bool = False,
ignore_init_module_imports: bool = False,
remove_all_unused_imports: bool = False,
remove_duplicate_keys: bool = False,
remove_unused_variables: bool = False,
remove_rhs_for_unused_variables: bool = False
) -> Iterable[str]def check(source: str) -> Iterable[pyflakes.messages.Message]Code Analysis and Transformation
Functions for processing individual files and directories with proper encoding detection, pattern matching, and batch operation support for integration into larger workflows.
def fix_file(
filename: str,
args: Mapping[str, Any],
standard_out: IO[str] | None = None
) -> intdef find_files(
filenames: list[str],
recursive: bool,
exclude: Iterable[str]
) -> Iterable[str]def is_python_file(filename: str) -> boolComprehensive configuration system supporting pyproject.toml and setup.cfg files with command-line argument merging for flexible deployment across different project structures.
def process_pyproject_toml(toml_file_path: str) -> MutableMapping[str, Any] | Nonedef merge_configuration_file(
flag_args: MutableMapping[str, Any]
) -> tuple[MutableMapping[str, Any], bool]def find_and_process_config(args: Mapping[str, Any]) -> MutableMapping[str, Any] | NoneFunctions for detecting and handling Python standard library imports, package names, and import patterns to ensure safe removal while preserving necessary functionality.
def standard_package_names() -> Iterable[str]def extract_package_name(line: str) -> str | Nonedef multiline_import(line: str, previous_line: str = "") -> boolclass ListReporter:
"""Accumulates pyflakes messages in a list for programmatic access."""
def __init__(self) -> None: ...
def flake(self, message: pyflakes.messages.Message) -> None: ...
class FilterMultilineImport:
"""Handles removal of unused imports from multiline import statements."""
def __init__(self, line: str) -> None: ...
def __call__(self, line: str) -> FilterMultilineImport | str: ...__version__: str # "2.3.1"
SAFE_IMPORTS: frozenset[str] # Standard library imports safe for removal
IMPORTS_WITH_SIDE_EFFECTS: set[str] # Known imports with side effectsdef main() -> intCommand-line interface entry point with comprehensive argument parsing, configuration file support, and signal handling for robust CLI operation.