µsort

1.1.3 · active · verified Sat Apr 11

µ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

Install

Imports

Quickstart

This example demonstrates how to use `usort` programmatically to sort imports in a Python file. It creates a temporary file with unsorted imports, applies `usort.usort_file` to sort it in-place, and then prints the sorted content.

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

view raw JSON →