isort - Python Import Sorter
What is isort?
isort is a Python utility designed to automatically sort your Python imports alphabetically and separate them into distinct sections. This tool significantly enhances code readability and maintainability by ensuring a consistent import structure across your projects. By automating the process of organizing imports, developers can focus more on writing functional code rather than spending time on manual formatting. isort helps enforce coding standards and reduces the likelihood of import-related errors.
How to Use isort
isort offers a flexible command-line interface to manage your Python imports. Here are some common usage examples:
Basic Usage
To sort imports in a single Python file:
isort my_script.py
Recursive Sorting
To sort imports in all Python files within the current directory and its subdirectories:
isort .
Viewing Changes (Diff)
To see the proposed changes without modifying the files:
isort my_script.py --diff
Verbose Output
To sort imports in place and display the changes made:
isort my_script.py --verbose
Profile Configuration
To sort imports using a specific profile, such as the 'black' style:
isort my_script.py --profile black
Checking for Unsorted Imports
To check if imports are sorted and get an error code if they are not:
isort my_script.py --check
Ignoring Files and Directories
To exclude specific files or directories from the sorting process:
isort . --skip some_directory --skip some_file.py
Custom Configuration Files
For more complex setups, you can use a custom configuration file:
isort . --settings-path path/to/.isort.cfg
Git Integration
To sort imports for all files in the current Git repository,
respecting your .gitignore
rules:
isort --git
Filtering by File Extension
To sort imports only for files with a specific extension (e.g.,
.py
):
isort . --ext py