Removes unused imports and unused variables from Python code
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Comprehensive configuration system supporting pyproject.toml and setup.cfg files with command-line argument merging. This enables flexible deployment across different project structures and integration with various build systems.
Functions for reading and processing configuration from standard Python project files.
def process_pyproject_toml(toml_file_path: str) -> MutableMapping[str, Any] | None:
"""
Extracts autoflake configuration from a pyproject.toml file.
Reads the [tool.autoflake] section from pyproject.toml and returns
the configuration as a dictionary suitable for merging with command-line args.
Args:
toml_file_path: Path to the pyproject.toml file
Returns:
Dictionary of configuration options, or None if file not found or no config
"""def process_config_file(config_file_path: str) -> MutableMapping[str, Any] | None:
"""
Extracts autoflake configuration from a setup.cfg style configuration file.
Reads the [autoflake] section from setup.cfg or similar INI-style configuration
files and returns parsed configuration options.
Args:
config_file_path: Path to the configuration file (setup.cfg, etc.)
Returns:
Dictionary of configuration options, or None if file not found or no config
"""Functions for automatically finding configuration files and merging them with command-line arguments.
def find_and_process_config(args: Mapping[str, Any]) -> MutableMapping[str, Any] | None:
"""
Finds and processes configuration files in the project directory.
Searches for pyproject.toml and setup.cfg files starting from the current
directory and moving up the directory tree to find project configuration.
Args:
args: Current command-line arguments (may contain config file path)
Returns:
Merged configuration from found files, or None if no config found
"""def merge_configuration_file(
flag_args: MutableMapping[str, Any]
) -> tuple[MutableMapping[str, Any], bool]:
"""
Merges configuration file settings with command-line arguments.
Combines settings from configuration files with command-line flags,
with command-line arguments taking precedence over file configuration.
Args:
flag_args: Command-line arguments as parsed by argparse
Returns:
Tuple of (merged_config, config_found) where:
- merged_config: Combined configuration dictionary
- config_found: Boolean indicating if configuration file was found
"""The following configuration options are supported in both file and command-line formats:
remove-all-unused-imports (bool): Remove all unused imports, not just standard libraryignore-init-module-imports (bool): Don't remove unused imports in __init__.py filesexpand-star-imports (bool): Replace from module import * with specific importsremove-unused-variables (bool): Remove unused variable assignmentsremove-duplicate-keys (bool): Remove duplicate keys in dictionaries and setsignore-pass-statements (bool): Don't remove pass statementsignore-pass-after-docstring (bool): Keep pass statements that come after docstringsin-place (bool): Modify files in place instead of printing to stdoutcheck (bool): Check if changes would be made (exit code indicates changes needed)recursive (bool): Process directories recursivelyexclude (list): Glob patterns for files/directories to excludeadditional-imports (list): Additional modules to treat as unused importsconfig (str): Path to specific configuration file[tool.autoflake]
remove-all-unused-imports = true
remove-unused-variables = true
remove-duplicate-keys = true
ignore-init-module-imports = true
exclude = ["__pycache__", "*.pyc", "tests/fixtures/*"]
additional-imports = ["django", "requests"][autoflake]
remove-all-unused-imports = true
remove-unused-variables = true
remove-duplicate-keys = true
ignore-init-module-imports = true
exclude = __pycache__,*.pyc,tests/fixtures/*
additional-imports = django,requestsimport autoflake
# Read from pyproject.toml
config = autoflake.process_pyproject_toml("pyproject.toml")
if config:
print("Found configuration:", config)
# Read from setup.cfg
config = autoflake.process_config_file("setup.cfg")
if config:
print("Found configuration:", config)import autoflake
# Automatically find and load configuration
args = {"recursive": True} # Some command-line args
config = autoflake.find_and_process_config(args)
if config:
print("Auto-discovered configuration:", config)
else:
print("No configuration file found")import autoflake
# Simulate command-line arguments
cli_args = {
"remove_unused_variables": True,
"in_place": True,
"recursive": False
}
# Merge with configuration file
merged_config, config_found = autoflake.merge_configuration_file(cli_args)
print(f"Configuration file found: {config_found}")
print(f"Final configuration: {merged_config}")
# Use the merged configuration
if merged_config.get("recursive"):
print("Will process directories recursively")import autoflake
import os
def load_project_config(project_dir):
"""Load autoflake configuration for a specific project."""
# Try pyproject.toml first
pyproject_path = os.path.join(project_dir, "pyproject.toml")
if os.path.exists(pyproject_path):
config = autoflake.process_pyproject_toml(pyproject_path)
if config:
return config, "pyproject.toml"
# Fall back to setup.cfg
setup_cfg_path = os.path.join(project_dir, "setup.cfg")
if os.path.exists(setup_cfg_path):
config = autoflake.process_config_file(setup_cfg_path)
if config:
return config, "setup.cfg"
return None, None
# Usage
config, config_file = load_project_config("./my_project")
if config:
print(f"Loaded configuration from {config_file}")
# Apply configuration to processing
for file_path in ["src/main.py", "src/utils.py"]:
autoflake.fix_file(file_path, config)import autoflake
import subprocess
import sys
def run_autoflake_with_config():
"""Run autoflake with project configuration and error handling."""
# Load configuration
merged_config, config_found = autoflake.merge_configuration_file({
"check": True, # Check mode - don't modify files
"recursive": True
})
if not config_found:
print("Warning: No configuration file found, using defaults")
# Find files to process
files = list(autoflake.find_files(
["src/"],
recursive=merged_config.get("recursive", False),
exclude=merged_config.get("exclude", [])
))
# Process files and track results
changes_needed = False
for file_path in files:
exit_code = autoflake.fix_file(file_path, merged_config)
if exit_code != 0:
changes_needed = True
if changes_needed:
print("Autoflake found issues that need fixing")
sys.exit(1)
else:
print("All files are clean")
sys.exit(0)
# Use in CI/CD pipeline
if __name__ == "__main__":
run_autoflake_with_config()Install with Tessl CLI
npx tessl i tessl/pypi-autoflake