0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ruff format (+ isort) を Python から使用できるようにする

Last updated at Posted at 2025-12-26

Ruff のフォーマッタには Python から使用できる API はないのかと思って探したが、なかった。1

ないものは作ればよい。

import subprocess
from tempfile import NamedTemporaryFile
from typing import Any


def ruff_format(
    code: str,
    *,
    ruff_command: str = "ruff",
    isort: bool = True,
    line_length: int | None = None,
) -> str:
    run_options: dict[str, Any] = {"text": True, "capture_output": True, "check": True}

    # isort
    if isort:
        with NamedTemporaryFile("w+", suffix=".py") as f:
            f.write(code)
            f.flush()
            cmd = [ruff_command, "check", "--isolated", "--fix"]
            cmd += ["--select", "I"]  # isort
            subprocess.run(cmd + [f.name], **run_options)
            f.seek(0)
            code = f.read()

    # format
    cmd = [ruff_command, "format", "--isolated"]
    if line_length:
        cmd += ["--line-length", str(line_length)]
    code = subprocess.run(cmd + ["-"], input=code, **run_options).stdout

    return code

使用例

from subprocess import CalledProcessError

code = """\
import sys, os
def add(a:int,b:int)->int:
  return a+b
print(add(1,2))
"""
try:
    print(ruff_format(code))
except CalledProcessError as exc:
    print(exc.stdout)

実行結果

import os
import sys


def add(a: int, b: int) -> int:
    return a + b


print(add(1, 2))
  1. Using ruff as a Python library · astral-sh/ruff · Discussion #8539

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?