python-import-sorter is designed to automatically sort and format import statements of Python code.
It groups imports based on predefined or custom categories and ensures a clean, structured order for better code readability and maintainability.
- Sorts
importandfrom ... import ...statements by line length first, then alphabetically - Groups imports based on predefined or custom categories
- Supports post-sorting formatting using external tools
- Works in-place or with standard input/output (
stdin/stdout)
Ensure you have Python 3.11+ installed.
You may also want to install a formatter like ruff for formatting:
pip install ruffTo install python-import-sorter directly from the repository:
pip install git+https://github.com/AntiMach/python-import-sorterRun the tool via Python:
python -m import_sorter <file>Or, if installed via pip, use the CLI directly:
import-sorter <file>-g, --groups: Define custom import groups (can be used multiple times)-f, --format: Specify a formatter to run after sorting (optional)-c, --config: Path to a config file with predefined arguments
Example:
import-sorter my_script.py -g numpy pandas -f "ruff format -"Arguments can be provided in several ways. The priority is as follows (highest to lowest):
- Command-line arguments (
--groups,--format, etc.) - Arguments from the file specified with
--config import-sorter.tomlin the current working directory.[tool.import-sorter]section ofpyproject.tomlat the current working directory.
Feel free to contribute by submitting pull requests or reporting issues.