isort
isort is a Python utility and library designed to sort imports alphabetically, automatically separating them into sections by type. It provides a command-line utility, a Python library, and plugins for various editors to streamline import organization. Currently at version 8.0.1, isort maintains an active development pace with frequent major and minor releases, ensuring ongoing feature enhancements and bug fixes.
Warnings
- breaking Major versions of `isort` regularly drop support for older Python versions. Version 7.0.0 dropped support for Python 3.9, and version 6.0.0 dropped Python 3.8. Current versions (8.x) require Python >= 3.10.0.
- breaking isort v8.0.0 removed the `setuptools` plugin and deprecated old finders flags and legacy finder logic. Version 6.1.0 also dropped the use of the non-standard `pkg_resources` API. Integrations relying on these components will break.
- gotcha `isort` can conflict with other code formatters, notably `Black`, if not configured correctly. Both tools format imports but with different default styles.
- gotcha `isort` supports multiple configuration file formats (`pyproject.toml`, `.isort.cfg`, `setup.cfg`, `tox.ini`, `.editorconfig`), which can lead to confusion regarding precedence and correct syntax. For `pyproject.toml`, settings must be under `[tool.isort]`.
- gotcha The `--atomic` flag, which prevents `isort` from applying changes that introduce syntax errors, is disabled by default. Using it can prevent `isort` from running against code written using a different Python version than the one `isort` is run with.
- gotcha Prior to version 8.0.0, `isort` had an edge case where it could incorrectly handle `__future__` imports. While fixed in 8.0.0, older versions might exhibit subtle issues.
Install
-
pip install isort
Imports
- isort
import isort
Quickstart
import isort
unsorted_code = '''import os
import sys
from third_party import lib
from . import local_module'''
sorted_code = isort.code(unsorted_code)
print(sorted_code)
# Example of checking if code is sorted correctly
is_sorted = isort.check_code(sorted_code)
print(f"Is the code sorted correctly? {is_sorted}")