autoflake
autoflake is a Python library and command-line tool that removes unused imports and unused variables from Python code. It aims to clean up source files by making minimal, focused changes. It is actively maintained by the PyCQA organization, with frequent minor releases, currently at version 2.3.3.
Warnings
- breaking autoflake dropped support for Python 3.8 starting from version 2.3.2. Ensure your environment uses Python 3.10 or newer.
- gotcha autoflake modifies files in-place when using the `--in-place` (or `-i`) flag in CLI. Always use it with version control to prevent accidental data loss.
- gotcha autoflake requires explicit flags to remove unused imports and variables (e.g., `--remove-all-unused-imports`, `--remove-unused-variables`). Without these, it might not perform any changes.
- gotcha TOML configuration support (`--config` flag) was introduced in v2.1.0, then reverted in v2.1.1, and re-introduced in v2.3.0. Using TOML config in versions 2.1.1 through 2.2.x will not work.
- gotcha autoflake is a linter focused on removing unused code elements; it is not a code formatter like Black or yapf. It will not reformat code style.
Install
-
pip install autoflake
Imports
- fix_code
from autoflake import fix_code
- fix_file
from autoflake import fix_file
Quickstart
import os
import autoflake
# Example file content with unused import and variable
example_code = """
import os # Unused
import sys
def my_func():
x = 10 # Unused
y = 20
print(sys.version, y)
"""
# Fix the code programmatically
cleaned_code = autoflake.fix_code(
example_code,
remove_all_unused_imports=True,
remove_unused_variables=True
)
print("Original code:\n" + example_code)
print("\nCleaned code:\n" + cleaned_code)
# --- CLI Usage Example (most common) ---
# Create a dummy file for CLI demonstration
dummy_file_path = "./temp_autoflake_example.py"
with open(dummy_file_path, "w") as f:
f.write(example_code)
print(f"\nCreated dummy file: {dummy_file_path}")
print("Running autoflake via CLI (simulated):")
# Simulate CLI command, usually run from shell
# import subprocess
# subprocess.run(["autoflake", "--in-place", "--remove-all-unused-imports", "--remove-unused-variables", dummy_file_path])
# To see the effect, you'd re-read the file after running the actual CLI command
# For this example, we'll just demonstrate the programmatic result.
# Clean up the dummy file
os.remove(dummy_file_path)
print(f"Removed dummy file: {dummy_file_path}")