A production-ready CLI tool that automatically detects and removes unused imports across Python projects safely.
- AST-based detection — Accurate unused import detection using Python's Abstract Syntax Tree
- Safe removal — Removes unused imports while preserving formatting
- Safety rules — Never removes imports inside
try/except ImportErroror referenced in__all__ - Dry-run mode — Preview what would be removed without making changes
- Diff preview — See exact changes before applying
- Recursive scanning — Scan entire projects with smart directory exclusion
- Configurable — Via
.importcleaner.toml,pyproject.toml, or CLI options - Pre-commit integration — Use as a pre-commit hook
- CI-friendly — Non-zero exit code when unused imports are found
pip install py-import-cleanerOr install from source:
git clone https://github.com/aneeshrao/py-import-cleaner.git
cd py-import-cleaner
pip install -e ".[dev]"py-import-cleaner .py-import-cleaner . --fixpy-import-cleaner . --dry-runpy-import-cleaner . --diff| Option | Description |
|---|---|
--fix |
Remove unused imports |
--dry-run |
Show results without changes |
--diff |
Show file diff of proposed changes |
--verbose |
Detailed logging |
--exclude |
Exclude directories (repeatable) |
--include |
Only scan selected paths (repeatable) |
--config |
Path to config file |
Create a .importcleaner.toml file in your project root:
[tool.importcleaner]
exclude = ["tests", "migrations"]
ignore_modules = ["typing"]Or add to your existing pyproject.toml:
[tool.importcleaner]
exclude = ["tests", "migrations"]
ignore_modules = ["typing"]Add to your .pre-commit-config.yaml:
repos:
- repo: https://github.com/aneeshrao/py-import-cleaner
rev: v1.0.0
hooks:
- id: py-import-cleaner3 unused imports found
accounts/views.py
line 3: import sys
utils/helpers.py
line 5: from datetime import datetime
Run with --fix to remove them
The tool will never remove imports that are:
- Inside
try/except ImportErrorblocks (optional dependency patterns) - Referenced in
__all__(public API exports)
# This import will NOT be removed
try:
import uvloop
except ImportError:
passfrom py_import_cleaner import analyze_source, fix_source
source = """
import os
import sys
print(os.getcwd())
"""
result = analyze_source(source)
for unused in result.unused_imports:
print(f"Unused: {unused}")
fixed = fix_source(source, result)
print(fixed)# Install dev dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Run linter
ruff check src/ tests/
# Run type checker
mypy src/import moduleimport module as aliasfrom module import namefrom module import name as aliasfrom module import name1, name2, name3
.git.venv/venv__pycache__node_modules.mypy_cache.pytest_cache.ruff_cache.toxdist/build
- Python >= 3.9
MIT