Skip to content

Instantly share code, notes, and snippets.

@jorenham
Last active May 20, 2025 16:41
Show Gist options
  • Save jorenham/63942278b01515ffdeb0c7d4d1895684 to your computer and use it in GitHub Desktop.
Save jorenham/63942278b01515ffdeb0c7d4d1895684 to your computer and use it in GitHub Desktop.
ruff format a Python string
import subprocess
from pathlib import Path
# see https://github.com/astral-sh/ruff/pull/18224
from ruff.__main__ import ( # type: ignore[import-untyped] # pyright: ignore[reportMissingTypeStubs]
find_ruff_bin, # noqa: PLC2701
)
def ruff_format(source: str) -> str:
result = subprocess.run(
[find_ruff_bin(), "format", "-"],
input=source,
text=True,
capture_output=True,
check=True,
cwd=Path.cwd(),
)
result.check_returncode()
return result.stdout
@jorenham
Copy link
Author

Compatible with mypy==1.15.0 and pyright==1.1.400 in strict mode.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment