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?

Python linter/formatter ruffの設定 (ruff, ruff-vscode, ruff-pre-commit)

Last updated at Posted at 2025-04-15

Ruff

RuffはPythonのlinter/formatterです。
便利なのですが、設定に関してはいくつか時間を使ってしまうところがあるので、簡単に書いておきます。

目指すべき姿

  • ruff check . --fix ruff format .でコードを修正できる
  • VSCodeのフォーマットでRuffを使うことができr
  • pre-commitでruffを実行できる

ruffの設定

ruff.toml or pyproject.tomlに記載していきます。

基本は、自分たちのプロジェクトでの設定になるのでこの設定が参照されるようにします。

例:

ruff.toml
line-length = 120 # line-lengthをcustomで設定

[lint]
select = [ 
  "E", # pycodestyle error
  "F", # Pyflakes
  "I", # isort
  "PLE", # PyLint
] # default: ["E4", "E7", "E9", "F"] Default以外のLinterも使う
ignore = ["E501"] # 特定のルールをignoreする

ruff-vscodeの設定

まずはVSCodeのExtension Ruffをインストールしておきます。

VSCodeの設定は、User settings, Workspace settingsなどがありますが、projectごとに設定する場合は projectの .vscode/settings.jsonに書いておくと同じルールを共有できて便利です。

.vscode/settings.json
{
    "[python]": {
        "editor.defaultFormatter": "charliermarsh.ruff"
    },
    "editor.codeActionsOnSave": {
        "source.fixAll.ruff": "explicit",
        "source.organizeImports.ruff": "explicit"
    },
    "ruff.configuration": "ruff.toml",
    "ruff.configurationPreference": "filesystemFirst"
}

こんな感じの設定にしておきます。

defaultFormatterをruffに指定したり、saveしたときのActionを設定したりできます。

configurationPreference は常にruff.tomlの設定を読み込むようにしています。一箇所で設定を管理したほうが、わかりやすいために明示的に設定ファイルを優先しておきます。

isortのextensionなどを入れているとConflictするケースがあるのでuninstallしておいたほうがいいかもしれません。(ちゃんとは確認してないですが)

設定詳細: https://github.com/astral-sh/ruff-vscode

ruff-pre-commitの設定

pre-commitを使ってruffをcommit時に確認すると便利です。

公式のruffのpre-commitがあるのでこちらを使います。

.pre-commit-config.yaml
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
  # Ruff version.
  rev: v0.11.5
  hooks:
    # Run the linter.
    - id: ruff
      types_or: [ python, pyi ]
      args: [ --fix ]
    # Run the formatter.
    - id: ruff-format
      types_or: [ python, pyi ]

このように設定して対象のレポジトリで pre-commit installとしておけばOkです。

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?