autoflake
Remove unused imports and variables
TLDR
Remove unused variables from a single file and display the diff
Remove unused imports from multiple files and display the diffs
Remove unused variables from a file, overwriting the file
Remove unused variables recursively from all files in a directory, overwriting each file
SYNOPSIS
autoflake [OPTIONS] [FILES]...
PARAMETERS
-r, --recursive
Traverse directories recursively
-i, --in-place
Make changes to files in place instead of printing diffs
--remove-all-unused-imports
Remove all unused imports, including those in type hints or docstrings
--remove-unused-variables
Remove unused local variables
--ignore-virtual-imports
Don't remove virtual imports (e.g., __version__)
--expand-star-imports
Expand star imports to explicit imports
--exclude=ATTR
Exclude attributes from removal (repeatable)
--remove-duplicate-keys
Remove duplicate keys in dictionary literals
--check-only
Check for unused code without modifying files
--dry-run
Show changes without applying them
-v, --verbose
Print more diagnostic messages
--version
Display version and exit
-h, --help
Show help message and exit
DESCRIPTION
Autoflake is a command-line tool designed to automatically clean Python source files by eliminating unused imports and unused local variables. It helps maintain code hygiene, reduce clutter, and improve readability without altering functionality.
By scanning Python files, autoflake identifies imports that are not referenced anywhere in the code and variables assigned but never used. It supports both single files and directories, with recursive processing available. Options allow customization, such as expanding star imports (e.g., from foo import *) into explicit imports or ignoring certain virtual imports like __version__.
This tool integrates well into development workflows, often used in pre-commit hooks or CI pipelines alongside formatters like Black. It preserves docstrings and type hints unless explicitly configured otherwise, ensuring safe refactoring. Autoflake is particularly useful for large codebases where manual cleanup is tedious.
CAVEATS
Requires Python and pip installation (pip install autoflake); modifies code irreversibly with --in-place—use --dry-run first. Not suitable for all Python versions; test thoroughly as it may alter imports in complex cases like dynamic loading.
INSTALLATION
Install via pip install autoflake. Available on PyPI; no system package in most distros.
EXAMPLE
autoflake -r --in-place --remove-unused-variables src/ cleans entire directory recursively.
HISTORY
Originally developed by Kevin Jacobs in 2013 as a simple script; evolved into a pip-installable package. Maintained on GitHub with contributions focusing on Python 3 compatibility and expanded features like duplicate key removal (added ~2018). Widely used in modern Python ecosystems.


