Skip to main content

A production-ready CLI tool that automatically detects and removes unused imports across Python projects safely.

Project description

py-import-cleaner

A production-ready CLI tool that automatically detects and removes unused imports across Python projects safely.

Features

  • 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 ImportError or 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

Installation

pip install py-import-cleaner

Or install from source:

git clone https://github.com/aneeshrao/py-import-cleaner.git
cd py-import-cleaner
pip install -e ".[dev]"

Quick Start

Scan for unused imports

py-import-cleaner .

Remove unused imports

py-import-cleaner . --fix

Preview changes (dry run)

py-import-cleaner . --dry-run

Show diff of proposed changes

py-import-cleaner . --diff

CLI Options

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

Configuration

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"]

Pre-commit Integration

Add to your .pre-commit-config.yaml:

repos:
  - repo: https://github.com/aneeshrao/py-import-cleaner
    rev: v1.0.0
    hooks:
      - id: py-import-cleaner

Example Output

3 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

Safety Rules

The tool will never remove imports that are:

  • Inside try/except ImportError blocks (optional dependency patterns)
  • Referenced in __all__ (public API exports)
# This import will NOT be removed
try:
    import uvloop
except ImportError:
    pass

Library Usage

from 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)

Development

# Install dev dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run linter
ruff check src/ tests/

# Run type checker
mypy src/

Supported Import Types

  • import module
  • import module as alias
  • from module import name
  • from module import name as alias
  • from module import name1, name2, name3

Default Excluded Directories

  • .git
  • .venv / venv
  • __pycache__
  • node_modules
  • .mypy_cache
  • .pytest_cache
  • .ruff_cache
  • .tox
  • dist / build

Requirements

  • Python >= 3.9

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

py_import_cleaner-1.0.0.tar.gz (20.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

py_import_cleaner-1.0.0-py3-none-any.whl (15.6 kB view details)

Uploaded Python 3

File details

Details for the file py_import_cleaner-1.0.0.tar.gz.

File metadata

  • Download URL: py_import_cleaner-1.0.0.tar.gz
  • Upload date:
  • Size: 20.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for py_import_cleaner-1.0.0.tar.gz
Algorithm Hash digest
SHA256 119f0af0f3007c417cec3c134bac77f943af122d13a7ddd8f23bcd32781945ba
MD5 233d66131232448701a5a2908b8ced9d
BLAKE2b-256 69023f93632b8dc79d54f3edca4c4bebbc5c7a76784e04a6282c48c1c9a9f147

See more details on using hashes here.

File details

Details for the file py_import_cleaner-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for py_import_cleaner-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6c15b7bb2044ba25c3d5a7fdcb3f983d74d2258f12917115191f962ebf7df856
MD5 036fc4342b07be0f4c74aa5f23291210
BLAKE2b-256 cb3adc1caf73186dbcba8ea69101f01128a8f671473ab9dd734deaa37ab75ad2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page