autoflake

2.3.3 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

The most common way to use autoflake is as a command-line tool. The quickstart shows programmatic usage with `autoflake.fix_code` and demonstrates the core flags. For CLI, `autoflake --in-place --remove-all-unused-imports --remove-unused-variables your_file.py` is typical.

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}")

view raw JSON →