µsort
µsort (pronounced 'micro-sort') is a Python utility for safe, minimal import sorting. Its primary goal is to reorder imports within detected 'blocks' without making dangerous changes or altering other code formatting. It works by identifying distinct import blocks and applying sorting rules based on common Python conventions. The current version is 1.1.3, and it maintains a public changelog for releases.
Warnings
- gotcha When using `usort format <path>` from the command line or `usort_file(..., write=True)` programmatically, `usort` modifies files in-place. Always ensure you have version control or backups if experimenting.
- gotcha To exclude specific imports from sorting or to act as block separators, use `comment markers` like `#usort:skip` or `#isort:skip` (for `isort` compatibility). Without these, `usort` will attempt to sort imports it deems safe within their blocks.
- gotcha `usort` relies on `LibCST` for parsing. For files containing Python 3.10+ specific syntax (like `match` statements), you might need to explicitly enable `LibCST`'s native PEG parser.
- gotcha The preferred method for configuring `usort` is via a `pyproject.toml` file, under the `[tool.usort]` table. `usort` will look for the nearest `pyproject.toml` upwards from the file being sorted.
Install
-
pip install usort
Imports
- usort_file
import usort from pathlib import Path # ... usort.usort_file(path_obj, write=True)
Quickstart
import usort
from pathlib import Path
import tempfile
# Create a dummy file with unsorted imports
code_to_sort = """
import sys
from os import path
import collections
"""
# Use a temporary file to demonstrate in-place sorting
with tempfile.NamedTemporaryFile(mode='w', suffix=".py", delete=False) as tmp_file:
tmp_file.write(code_to_sort)
tmp_file_path = Path(tmp_file.name)
try:
print(f"Original file content:\n---\n{code_to_sort.strip()}\n---")
# Sort the file in-place
result = usort.usort_file(tmp_file_path, write=True)
if result.error:
print(f"Error sorting file: {result.error}")
else:
with open(tmp_file_path, 'r') as f:
sorted_code = f.read()
print(f"Successfully sorted {tmp_file_path.name}")
print(f"Sorted file content:\n---\n{sorted_code.strip()}\n---")
finally:
tmp_file_path.unlink() # Clean up the temporary file