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?

More than 1 year has passed since last update.

Python でリンター兼フォーマッターを高速で Ruff で実現

Last updated at Posted at 2023-10-31

Ruff とは

Pythonのリンター兼フォーマッターであり、高速であることが特徴なようです。

チュートリアル

ruff のインストール

pip install ruff

サンプルの準備

numbers.py
from typing import Iterable

import os


def sum_even_numbers(numbers: Iterable[int]) -> int:
    """Given an iterable of integers, return the sum of all even numbers in the iterable."""
    return sum(
        num for num in numbers
        if num % 2 == 0
    )

ruff check

ruff checkを実行することにより、リンターを実行。

Ruff % ruff check .

numbers.py:3:8: F401 [*] `os` imported but unused
Found 1 error.
[*] 1 fixable with the `--fix` option.

osはインポートされましたが、利用していないというメッセージです。

ruff check --fixを実行することにより自動で修正してくれます。

ruff check --fix .
Found 1 error (1 fixed, 0 remaining).

ruff format

ruff formatを実行することにより、フォーマッターを実行。

ruff format .
1 file reformatted

動作のカスタマイズ

Ruff の動作をカスタマイズすることが可能です。

プロジェクトのルートディレクトリにpyproject.tomlファイルを以下の通り作成し、ruff checkを実行します。

pyproject.toml
[tool.ruff]
# 行の最大長を79に設定する。
line-length = 79

[tool.ruff.lint]
# line-too-long`ルールを強制ルールセットに追加します。デフォルトでは、Ruffは以下のようなルールを除外する。
# ブラックのようにフォーマッタの使用と重複するルールは省略されますが、 
# 明示的にルールを追加することでこの動作をオーバーライドできます.
extend-select = ["E501"]

最大長が強制され、制限は 79 にしてほしいというメッセージが表示されます。

ruff check .
numbers.py:5:80: E501 Line too long (92 > 79)
Found 1 error.

GitHub Actions

ついでなので、GitHub Actions に組み込んで試してみたいと思います。

.github/workflows/ruff.yml
name: Ruff
on: [push, pull_request]
jobs:
  ruff:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: chartboost/ruff-action@v1

先程と同じようにosはインポートされましたが、利用していないというメッセージのところでエラーになったことがわかります。

スクリーンショット 2023-10-31 20.24.32.png

デフォルトの動作からカスタマイズする必要はあるでしょうが、簡単にCIに組み込むことができるのは良いですね。

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?