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?

Claude3.7にオススメされたPython環境設定 - poetry, ruff etc.

Posted at

新規プロジェクトでRuffを中心とした開発環境を構築する場合、より包括的な構成が可能です。新しいコードベースでは厳格なルールを最初から適用できるため、より高品質なコードを維持しやすくなります。以下に最適な構成を示します:

パッケージとツール構成

# Poetryのインストール
curl -sSL https://install.python-poetry.org | python3 -

# プロジェクト初期化
poetry new my-project
cd my-project

# 開発依存関係の追加
poetry add --group dev ruff mypy pytest pytest-cov pre-commit

pyproject.toml 設定

[tool.poetry]
name = "my-project"
version = "0.1.0"
description = "新規プロジェクトの説明"
authors = ["Your Name <your.email@example.com>"]
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.10"

[tool.poetry.group.dev.dependencies]
ruff = "^0.1.5"
mypy = "^1.6.1"
pytest = "^7.4.3"
pytest-cov = "^4.1.0"
pre-commit = "^3.5.0"

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

# Ruffの包括的な設定
[tool.ruff]
# すべてのルールを有効化
select = ["ALL"]
# プロジェクトの状況に応じて必要なルールの除外
ignore = []
# Python のバージョン
target-version = "py310"
# 行の長さ
line-length = 88

# 特に重要なルールの設定
[tool.ruff.per-file-ignores]
# テストファイルでは一部のルールを緩和
"tests/**/*.py" = ["ANN", "D"]
# ドキュメント関連のファイルでもルール緩和
"docs/**/*.py" = ["D"]

# ドキュメント文字列のスタイル
[tool.ruff.pydocstyle]
convention = "google"

# 命名規則
[tool.ruff.flake8-tidy-imports]
ban-relative-imports = "all"

# 未使用import自動削除
[tool.ruff.isort]
combine-as-imports = true
force-single-line = false

# フォーマッター設定
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
line-ending = "auto"
docstring-code-format = true

# mypy設定
[tool.mypy]
python_version = "3.10"
disallow_untyped_defs = true
disallow_incomplete_defs = true
check_untyped_defs = true
disallow_untyped_decorators = true
no_implicit_optional = true
strict_optional = true
warn_redundant_casts = true
warn_return_any = true
warn_unused_ignores = true
warn_unused_configs = true

# Pytestの設定
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = "test_*.py"
python_classes = "Test*"
python_functions = "test_*"
addopts = "--cov=my_project --cov-report=xml --cov-report=term"

.pre-commit-config.yaml

repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.5.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-toml
      - id: check-added-large-files
      - id: debug-statements
      - id: detect-private-key

  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.1.5
    hooks:
      - id: ruff
        args: [--fix, --exit-non-zero-on-fix]
      - id: ruff-format

  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.6.1
    hooks:
      - id: mypy
        additional_dependencies: [types-all]

  # コミットメッセージのルール
  - repo: https://github.com/commitizen-tools/commitizen
    rev: v3.12.0
    hooks:
      - id: commitizen

プロジェクト構造の初期化

# pre-commitインストール
poetry run pre-commit install
poetry run pre-commit install --hook-type commit-msg

# 初期テストディレクトリ設定
mkdir -p tests

# README追加
cat > README.md << EOF
# My Project

プロジェクトの説明をここに記載

## インストール

\`\`\`bash
pip install my-project
\`\`\`

## 開発環境セットアップ

\`\`\`bash
# 依存関係のインストール
poetry install

# pre-commitフックの設定
poetry run pre-commit install
\`\`\`
EOF

# GitHub Actions CI設定
mkdir -p .github/workflows
cat > .github/workflows/ci.yml << EOF
name: CI

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        with:
          python-version: '3.10'
      - name: Install Poetry
        run: curl -sSL https://install.python-poetry.org | python3 -
      - name: Install dependencies
        run: poetry install
      - name: Lint with Ruff
        run: poetry run ruff check .
      - name: Format with Ruff
        run: poetry run ruff format --check .
      - name: Check types with mypy
        run: poetry run mypy .
      - name: Test with pytest
        run: poetry run pytest
EOF

VSCode 設定 (.vscode/settings.json)

{
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.organizeImports.ruff": true,
    "source.fixAll.ruff": true
  },
  "python.linting.enabled": true,
  "python.linting.mypyEnabled": true,
  "python.testing.pytestEnabled": true,
  "python.testing.unittestEnabled": false,
  "python.testing.nosetestsEnabled": false,
  "python.testing.pytestArgs": [
    "tests"
  ],
  "[python]": {
    "editor.defaultFormatter": "charliermarsh.ruff",
    "editor.formatOnSave": true,
    "editor.rulers": [88]
  },
  "files.trimTrailingWhitespace": true,
  "files.insertFinalNewline": true
}

この構成の特徴は:

  1. Ruffのselect = ["ALL"]で利用可能なすべてのルールを有効化
  2. 新規プロジェクトで重要な型ヒントの厳格な設定
  3. テスト環境とカバレッジレポートの組み込み
  4. CI/CDパイプラインの初期設定
  5. コミットメッセージ規約の採用
  6. エディタ設定の自動化

新規プロジェクトでは、初めから高品質なコード規約を適用することで、後々のリファクタリングの必要性を減らし、メンテナンス性の高いコードベースを構築できます。必要に応じて、プロジェクトの進行とともにルールを調整していくことも可能です。

既存の場合

Ruffを中心とした最適な Python 開発環境の構成について説明します:

基本ツール

  1. パッケージ管理: Poetry
  2. リンティング/フォーマット: Ruff(主要ツールとして)
  3. 静的型チェック: mypy
  4. 自動化: pre-commit

インストール方法

# Poetry のインストール
curl -sSL https://install.python-poetry.org | python3 -

# プロジェクト初期化
poetry init

# 開発依存関係の追加
poetry add --group dev ruff mypy pre-commit

設定ファイル例

pyproject.toml:

[tool.poetry]
name = "your-project"
version = "0.1.0"
description = "Your project description"
authors = ["Your Name <your.email@example.com>"]

[tool.poetry.dependencies]
python = "^3.9"

[tool.poetry.group.dev.dependencies]
ruff = "^0.1.0"
mypy = "^1.5.0"
pre-commit = "^3.4.0"

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

[tool.ruff]
# Ruffですべての検証を行う設定
line-length = 88
target-version = "py39"
# E, F: pycodestyle, pyflakes
# I: isort
# D: pydocstyle
# N: pep8-naming
# ANN: flake8-annotations
# B: flake8-bugbear
# C4: flake8-comprehensions
# SIM: flake8-simplify
# TCH: flake8-type-checking
# ERA: eradicate
select = ["E", "F", "I", "D", "N", "ANN", "B", "C4", "SIM", "TCH", "ERA"]
ignore = []

# Ruffのフォーマッター機能を有効化
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
line-ending = "auto"

[tool.mypy]
python_version = "3.9"
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
disallow_incomplete_defs = true

.pre-commit-config.yaml:

repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.4.0
    hooks:
    -   id: trailing-whitespace
    -   id: end-of-file-fixer
    -   id: check-yaml
    -   id: check-toml

-   repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.1.0
    hooks:
    -   id: ruff
        args: [--fix]
    -   id: ruff-format

-   repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.5.0
    hooks:
    -   id: mypy
        additional_dependencies: [types-all]

pre-commit の設定

# pre-commit をリポジトリに設定
poetry run pre-commit install

VSCode 設定 (settings.json)

{
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll": true
  },
  "python.linting.enabled": true,
  "python.linting.mypyEnabled": true,
  "python.formatting.provider": "none",
  "[python]": {
    "editor.defaultFormatter": "charliermarsh.ruff"
  }
}

この構成では:

  • Ruff が単一ツールとして lint と format を担当
  • mypy が静的型チェックを提供
  • pre-commit が git コミット前の自動検証を実行
  • Poetry がパッケージと仮想環境を管理

これにより、複数のツールの重複を避けながら、高品質なコード開発環境を維持できます。必要に応じて CI/CD パイプラインにも同じチェックを組み込むと良いでしょう。

Allと比べて抜けてる部分

Ruffでselect = ["all"]とした場合と比較して、先ほど提案した特定のルールセットを選択した構成では、いくつかのルールセットが除外されています。

除外されているのは主に以下のようなルールセットです:

  1. PLR (Pylint Refactor) - Pylintのリファクタリング関連の提案
  2. PLW (Pylint Warning) - Pylintの警告
  3. PLE (Pylint Error) - Pylintのエラー
  4. FLY (flynt) - f-strings への自動変換
  5. BLE (flake8-blind-except) - 例外の捕捉に関する警告
  6. FBT (flake8-boolean-trap) - ブール値パラメータの使用に関する警告
  7. COM (flake8-commas) - カンマの使用に関するスタイル
  8. DTZ (flake8-datetimez) - datetime関数の使用に関する警告
  9. T10 (flake8-debugger) - デバッガー関数の検出
  10. EM (flake8-errmsg) - エラーメッセージのフォーマット
  11. ICN (flake8-import-conventions) - インポート規約
  12. PD (pandas-vet) - pandas使用に関するベストプラクティス
  13. PT (flake8-pytest-style) - pytestスタイルに関する規約
  14. RUF (Ruff-specific) - Ruff固有のルール

select = ["all"]とすると、利用可能なすべてのルールセットが有効になるため、非常に厳格なチェックが行われます。これは新規プロジェクトでは有用かもしれませんが、既存のコードベースではあまりにも多くの警告が発生する可能性があります。

先ほど提案した選択的なルールセット(E, F, I, D, N, ANN, B, C4, SIM, TCH, ERA)は、一般的に以下のバランスを取ろうとしています:

  1. 基本的なPEP 8スタイルとコードエラー(E, F)
  2. インポート整理(I)
  3. ドキュメンテーション(D)
  4. 命名規則(N)
  5. 型アノテーション(ANN)
  6. バグになりうるパターン(B)
  7. リスト内包表記の最適化(C4)
  8. コード簡素化の提案(SIM)
  9. 型チェック関連(TCH)
  10. 使われていないコードの除去(ERA)

プロジェクトの性質や要件に応じて、個別のルールセットを追加または除外することで、より適切なバランスを見つけることができます。例えば、Pandasを多用するデータサイエンスプロジェクトではPDを追加したり、テスト駆動開発を重視するプロジェクトではPTを追加したりすることが考えられます。

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?