Python Linter로 Ruff를 사용해보기(feat. pre-commit)

Juheon Oh·2023년 3월 19일
0

Ruff란?

Rust로 만든 매우 빠른 Python Linter
2022년에 공개된 후 Star가 빠른 속도로 증가 중 (깃허브 링크)

Features

  • 기존 Linter보다 약 10~100배 빠름
  • pip로 설치 가능
  • pyproject.toml로 config를 관리함
  • Autofix가 지원 가능함
    • 단순 error를 잡아주는 것이 아니라 Fix까지 해줌 (Flake8과 다르게)
  • Flake8, isort, pydocstyle, yesqa, eradicate, pyupgrade, autoflake 대신 Ruff 하나로 대체 가능
    • 이외에도 다양한 패키지 지원 (참고)
  • Pandas, FastAPI, Apache Airflow에서도 Linter로 사용 중
  • 나중에는 type checker도 탑재할 계획

안 쓸 이유가..? 없다..!

pre-commit에서 Ruff 사용

pre-commit-config.yaml

  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.4.0
    hooks:
      - id: check-yaml
      - id: end-of-file-fixer
      - id: trailing-whitespace
  - repo: https://github.com/charliermarsh/ruff-pre-commit
    rev: 'v0.0.256'
    hooks:
      - id: ruff
        args: ["--fix"]

repo에 ruff를 추가해주고 원하는 버전을 추가해주면 된다.
autofix기능을 사용하고 싶다면 args에 --fix를 추가해준다.

pyproject.toml

# ref: https://beta.ruff.rs/docs/rules/
select = ["B", "C4", "E", "F", "N", "I", "W", "UP"]
ignore = ["F403","F405","E501","E402"]

# Allow autofix for all enabled rules (when `--fix`) is provided.
fixable = ["A", "B", "C", "D", "E", "F", "I", "UP"]
unfixable = []

per-file-ignores = {}

# Same as Black.
line-length = 88

# Allow unused variables when underscore-prefixed.
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"

# Assume Python 3.9.
target-version = "py39"

[tool.ruff.mccabe]
# Unlike Flake8, default to a complexity level of 10.
max-complexity = 10

Ruff는 toml로 config를 관리한다.(참고)

공식 문서를 참고해서 괜찮은 플러그인들을 적용했다.

select에 있는 rule들이 내가 사용하는 플러그인이고, ignore는 사용하지 않는 플러그인이다.

select에 있는 rule 중 사용하고 싶지 않은 code들이 있다면 ignore에 넣어주면 된다.

ex) E는 사용하지만 E501은 사용하고 싶지 않을때
`E501 - “Line too long ({length} > {limit} characters)“` ([참고](https://beta.ruff.rs/docs/rules/#pycodestyle-e-w))

Ruff는 autofix도 지원하기 때문에 사용하고 싶은 플러그인을 fixable에 넣어주면 된다.

0개의 댓글