ufmt: Safe, Atomic Formatting with Black and µsort

2.9.1 · active · verified Sat Apr 11

ufmt (pronounced "micro-fmt") is a safe, atomic code formatter for Python, built on top of the popular `black` formatter and `µsort` import sorter. It combines their functionality into a single, atomic step, ensuring consistent code style and import order without intermediate conflicts. Currently at version 2.9.1, it requires Python 3.10 or newer and maintains an active release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `ufmt_file` API to programmatically format a Python file. It creates a temporary file, formats it with `ufmt`, prints the original and formatted content, and then cleans up the temporary file. For simple command-line usage, run `ufmt format <path>` in your terminal.

import os
from pathlib import Path
from ufmt import ufmt_file
from black import Mode, TargetVersion
from usort import Config

def main():
    # Create a dummy Python file
    dummy_content = (
        "import os, sys\n\ndef my_func ( param1,  param2 ) :\n    \"\"\"A docstring.\"\"\"\n    return  param1  + param2\n"
    )
    dummy_file = Path("temp_module.py")
    dummy_file.write_text(dummy_content)

    print(f"Original content of {dummy_file.name}:\n---\n{dummy_content.strip()}\n---")

    # Define black and usort configs (optional, ufmt can detect from pyproject.toml)
    # For this example, we provide minimal configs
    black_config = Mode(target_versions={TargetVersion.PY310})
    usort_config = Config()

    # Format the file using the ufmt API
    result = ufmt_file(
        path=dummy_file,
        black_config=black_config,
        usort_config=usort_config,
        return_content=True
    )

    if result.error:
        print(f"Error formatting {dummy_file.name}: {result.error}")
    elif result.changed:
        print(f"Formatted content of {dummy_file.name}:\n---\n{result.after.decode().strip()}\n---")
    else:
        print(f"{dummy_file.name} was already formatted correctly.\n---\n{result.after.decode().strip()}\n---")

    # Clean up the dummy file
    dummy_file.unlink()

if __name__ == "__main__":
    main()

view raw JSON →