reorder-python-imports

raw JSON →
3.16.0 verified Mon Apr 27 auth: no python

A tool for automatically reordering Python imports into a consistent style (stdlib, third-party, first-party) and removing unused imports. Current version: 3.16.0. Released irregularly, maintained by asottile.

pip install reorder-python-imports
error ModuleNotFoundError: No module named 'reorder_python_imports'
cause Package not installed or installed with a different name.
fix
Run: pip install reorder-python-imports
error reorder-python-imports: error: unrecognized arguments: --amazing-option
cause Using a flag that does not exist in current version.
fix
Check CLI options with: reorder-python-imports --help
breaking Version 3.x dropped Python 2 support and changed default behavior to remove unused imports. If relying on version 2.x behavior, pin to 'reorder-python-imports<3'.
fix Pin to version 2.x if needed: pip install 'reorder-python-imports<3'
gotcha The tool reorders imports within a single file only; it does not handle cross-module analysis. Unused imports are removed based on simple AST check, which may remove imports used via eval or sys.modules.
fix Manually verify that imports used dynamically are not removed. Use '--no-remove-unused' flag to disable removal.
gotcha Import comments or inline type hints (e.g., 'from typing import TYPE_CHECKING') may be lost if not recognized. The tool strips comments and may reorder them incorrectly.
fix Place type-checking imports in a separate block or use '# noqa' comments judiciously; review output.

Reorder imports via CLI or programmatically. The fix_file_contents function returns reordered code.

# As a CLI tool:
# reorder-python-imports myfile.py

# As a library:
import reorder_python_imports

code = """import os
import sys
import requests
"""
result = reorder_python_imports.fix_file_contents(code)
print(result)