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?

#0193(2025/07/12)Python Wheel 入門

Last updated at Posted at 2025-07-11

Python Wheel 入門

1. Wheel とは何か

  • 定義: Python パッケージを “ビルド済みバイナリ + メタデータ” にまとめたアーカイブ(.whl 拡張子)。PEP 427 で標準化。

  • 目的: インストールを高速化 し、ビルド環境差異によるトラブルを削減する。

  • 仕組み: zip 互換フォーマット。ファイル名に Python バージョン / ABI / プラットフォーム タグが入り、互換性を明示。

  • 生成コマンド例:

    # PEP 517 推奨
    python -m build --wheel  # dist/*.whl が出力される
    
  • インストール:

    pip install ./dist/pkg-1.0-py3-none-any.whl  # unzip だけで完了
    

2. Wheel ファイルの内部構造

  • 主要フォルダ

    • pkg_name/ … ピュア Python もしくは C 拡張(.so/.pyd)
    • pkg_name‑VERSION.dist-info/ … メタデータ: METADATA, RECORD, entry_points.txt
  • 特徴

    • コンパイル済み ファイルを含められる → インストール時にコンパイラ不要
    • RECORD にファイルの SHA256 ハッシュが記録され、改ざん検出に利用可能

3. 配布形式の比較

観点 Wheel (.whl) Source Distribution (sdist) Egg (.egg)
ビルド要否 不要(事前) 必要(インストール時) 不要(事前)
推奨度 ★★★ (現在の標準) ★★ (Fallback) ★ (旧式)
プラットフォーム依存 あり (manylinux, win_amd64 等) なし あり
メタデータ仕様 PEP 427 PEP 517/518 非推奨独自
pip の扱い 1st choice 2nd choice 読み取り可・生成不可

4. Wheel と Docker Build の関係

  • レイヤーキャッシュ最適化

    1. 依存パッケージを wheel キャッシュに変換

      RUN pip wheel --wheel-dir=/tmp/wheels -r requirements.txt
      
    2. アプリ層で wheel をコピーしてインストール

      COPY --from=builder /tmp/wheels /wheels
      RUN pip install --no-index --find-links=/wheels myapp[all]
      
    3. 依存が変わらない限り /tmp/wheels レイヤーが再利用され、ビルド時間を大幅短縮。

  • マルチステージとの相性: ビルド専用イメージで heavy なツールチェーンを使い、最終イメージには wheel + runtime のみ持ち込むことで イメージを数百 MB 削減

5. CI/CD への応用

  • 戦略① – Pre‑build Wheel Cache

    • CI ジョブで wheel を生成 → アーティファクト保存
    • デプロイ段階では pip install --no-index --find-links で高速展開。
  • 戦略② – プラットフォーム別 Wheel 配布

    • GitHub Actions の [cibuildwheel] を使い、Linux/macos/Windows 向け wheel を一括生成。
    • 成果物を PyPI もしくは私設リポジトリ(Artifactory など)へ upload。
  • 戦略③ – セキュリティ & 再現性

    • pip install --require-hashesRECORD ハッシュでサプライチェーン攻撃をブロック。
    • Tag & Release ごとに wheel ハッシュを lockfile に記録しておくと再現性◎。

6. よくあるハマりどころと対策

  • C 拡張を含む wheel: manylinux タグ未対応の古い glibc で動かない → build イメージを quay.io/pypa/manylinux_2_28_x86_64 に統一
  • --no-binary :all: を明示している Dockerfile で wheel が無視される → only-binary/no-binary のフラグを精査。
  • 大規模 monorepo: サブパッケージごとに wheel を切る or namespace package で 1 wheel 化、どちらが最適か検討が必要。

7. まとめ & 次のステップ

  • Wheel は “事前コンパイルされた決定版パッケージ”。 インストール速度・環境依存性・セキュリティいずれもメリット大。
  • Docker Build では wheel キャッシュ+マルチステージがベストプラクティス
  • CI/CD で wheel を生成・署名・配布 する仕組みを整えると、再現性と配布効率が飛躍的に向上。
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?