본문 바로가기
C.W.K.
Stream
Lesson 04 of 05 · published

ruff·mypy·pre-commit — 빠른 정적 피드백

~18 min · ruff, mypy, lint, type-check

Level 0호기심
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete

ruff는 Rust로 만든 빠른 린터이자 포매터야. flake8·pycodestyle·isort 계열의 많은 검사를 한 설정으로 묶어 스타일, 가져오기, 죽은 코드, 보안 냄새를 찾고 안전한 것은 ruff check --fix로 고쳐. ruff format은 코드 모양을 맞춰.

mypy는 타입 힌트를 읽어 사용이 선언된 계약과 맞는지 검사해. 새 프로젝트는 엄격 모드가 좋은 출발점이고, 오래된 코드는 범위를 넓혀 가는 편이 현실적이야. pyright는 빠른 추론을 제공하며 Pylance의 기반이라 편집기에는 pyright, 지속 통합에는 mypy를 함께 쓰는 팀도 있어.

pre-commit은 커밋 전에 ruff·mypy·pytest 같은 검사를 자동 실행해. 하지만 포매터는 모양, 린터는 알려진 냄새, 타입 검사기는 선언한 계약만 봐. 실제 사용자 흐름과 설치된 실행 시점은 별도로 검증해야 해.

Code

ruff 설치와 검사·bash
pip install ruff

# 코드 체크
ruff check .

# 자동 fix
ruff check . --fix

# 포맷 (많이 black 대체)
ruff format .

# 흔한 출력:
# my_module.py:42:5: E711 Comparison to None should be 'x is None'
# Found 1 error.
# [*] 1 fixable with the --fix option.
pyproject.toml의 ruff 설정·toml
[tool.ruff]
line-length = 100
target-version = "py310"

[tool.ruff.lint]
select = [
    "E",    # pycodestyle 에러
    "F",    # Pyflakes
    "W",    # pycodestyle 경고
    "I",    # isort
    "UP",   # pyupgrade
    "B",    # flake8-bugbear
    "C4",   # flake8-comprehensions
]
ignore = ["E501"]    # 줄 너무 김 (formatter 가 처리)

[tool.ruff.format]
quote-style = "double"
# preview 기능 활성화
preview = false
mypy로 타입 계약 확인하기·bash
pip install mypy

# 파일 체크
mypy my_module.py

# 전체 프로젝트 체크
mypy .

# 엄격 모드 — 새 코드에 권장
mypy --strict .

# 출력:
# my_module.py:42: error: Incompatible return type (got 'int', expected 'str')
# Found 1 error in 1 file (checked 5 files)
pyproject.toml의 mypy 설정·toml
[tool.mypy]
python_version = "3.10"
strict = true

# 모듈별 override
[[tool.mypy.overrides]]
module = "third_party_lib.*"
ignore_missing_imports = true

[[tool.mypy.overrides]]
module = "my_legacy_module.*"
disallow_untyped_defs = false      # gradual typing 동안 untyped 허용
pre-commit으로 커밋 전에 검사하기·yaml
# .pre-commit-config.yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.4.0
    hooks:
      - id: ruff
        args: [--fix]
      - id: ruff-format

  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.10.0
    hooks:
      - id: mypy

# hook 한 번 설치:
# pip install pre-commit
# pre-commit install
# 이제 모든 git commit 이 변경된 파일에 ruff + mypy 실행

External links

Exercise

작은 프로젝트에 ruff와 mypy를 설치하고 pyproject.toml에 strict 설정을 둬. -> int 함수가 문자열을 돌려주는 타입 오류를 mypy로 잡아 고치고, 쓰지 않는 import를 ruff check로 확인해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.