🐍

Hatch is a modern, extensible Python project manager

2022/10/16に公開

Hatch

Hatch is a modern, extensible Python project manager.
Pythonのプロジェクトマネージャです。ドキュメントの通りにやってみる。


(かわいい...)
https://hatch.pypa.io/latest/

https://packaging.python.org/ja/latest/key_projects/#hatch

Hatch は、 Python での開発者向けに依存関係の管理や環境の分離を便利に行うための統合されたコマンドラインツールです。 Python パッケージ開発者は Hatch とそのビルド用のバックエンドである Hatchling を使って、パッケージの設定を実施し、バージョン管理を行い、依存関係を指定し、そして PyPI で公開することができます。プラグインシステムがあるので、容易に機能を拡張することができます。

Documentに従って進めてみる

以下の環境で実行します。

❯ python -V
Python 3.10.2

Installation

https://hatch.pypa.io/latest/install/

❯ pip install hatch
❯ hatch --version
Hatch, version 1.6.0

Start a new project

❯ hatch new "Hatch Demo"
❯ hatch version
0.0.1

とすると、hatch-demoというディレクトリとファイル群が以下のように作成される。

❯ tree
.
└── hatch-demo
    ├── LICENSE.txt
    ├── README.md
    ├── hatch_demo
    │   ├── __about__.py
    │   └── __init__.py
    ├── pyproject.toml
    └── tests
        └── __init__.py

既存プロジェクトでは、以下のようにはじめられます。

❯ hatch new --init

Create a new environment

新しい環境を作成する。

❯ hatch env create

作成された環境があるか確認する。

❯ hatch env show
     Standalone
┏━━━━━━━━━┳━━━━━━━━━┓
┃ Name    ┃ Type    ┃
┡━━━━━━━━━╇━━━━━━━━━┩
│ default │ virtual │
└─────────┴─────────┘

pyproject.tomlにコマンドを用意しておけば、実行してくれます。(最近は設定ファイルにrun-scriptを書くのが増えてますね。便利。)

[tool.hatch.envs.default.scripts]
cov = "pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=hatch_demo --cov=tests {args}"
no-cov = "cov --no-cov {args}"
❯ hatch run cov
============================================================== test session starts ==============================================================
platform darwin -- Python 3.10.2, pytest-7.1.3, pluggy-1.0.0
rootdir: /Users/***/try-hatch/hatch-demo
plugins: cov-4.0.0
collected 0 items
/Users/***/Library/Application Support/hatch/env/virtual/hatch-demo/m24ha60x/hatch-demo/lib/python3.10/site-packages/coverage/control.py:801: CoverageWarning: No data was collected. (no-data-collected)
  self._warn("No data was collected.", slug="no-data-collected")


---------- coverage: platform darwin, python 3.10.2-final-0 ----------
Name                     Stmts   Miss  Cover   Missing
------------------------------------------------------
hatch_demo/__init__.py       0      0   100%
tests/__init__.py            0      0   100%
------------------------------------------------------
TOTAL                        0      0   100%

scriptの実行。

[tool.hatch.envs.default]
dependencies = [
  "pytest",
  "pytest-cov",
  "cowsay",
]
[tool.hatch.envs.default.scripts]
cov = "pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=hatch_demo --cov=tests {args}"
no-cov = "cov --no-cov {args}"

[[tool.hatch.envs.test.matrix]]
python = ["37", "38", "39", "310", "311"]

# 以下は追加してみた。
[[tool.hatch.envs.test2.matrix]]
python = ["38", "39", "310"]
❯ hatch env create

tomlに以下のパスが存在すれば、以下のように作成することができます。

❯ hatch env create test
❯ hatch env create test2  # 追加した

  • Scriptsの欄にあるのはhatch run covなどで実行可能

Pythonのファイルを作成して実行してみる

以下のPythonスクリプトをhatch_demo/main.py として保存して実行してみる。

import sys

print(sys.version)
print("hello")
❯ hatch run python hatch_demo/main.py
3.10.2 (main, Aug  2 2022, 01:13:09) [Clang 13.0.0 (clang-1300.0.27.3)]
hello

ヘルプ

ヘルプを見てみる。気になるのがあれば探ってみましょう。

❯ hatch -h
Usage: hatch [OPTIONS] COMMAND [ARGS]...

   _   _       _       _
  | | | |     | |     | |
  | |_| | __ _| |_ ___| |__
  |  _  |/ _` | __/ __| '_ \
  | | | | (_| | || (__| | | |
  \_| |_/\__,_|\__\___|_| |_|

Options:
  -e, --env TEXT                  The name of the environment to use [env var:
                                  `HATCH_ENV`]
  -p, --project TEXT              The name of the project to work on [env var:
                                  `HATCH_PROJECT`]
  --color / --no-color            Whether or not to display colored output
                                  (default is auto-detection) [env vars:
                                  `FORCE_COLOR`/`NO_COLOR`]
  --interactive / --no-interactive
                                  Whether or not to allow features like
                                  prompts and progress bars (default is auto-
                                  detection) [env var: `HATCH_INTERACTIVE`]
  -v, --verbose                   Increase verbosity (can be used additively)
                                  [env var: `HATCH_VERBOSE`]
  -q, --quiet                     Decrease verbosity (can be used additively)
                                  [env var: `HATCH_QUIET`]
  --data-dir TEXT                 The path to a custom directory used to
                                  persist data [env var: `HATCH_DATA_DIR`]
  --cache-dir TEXT                The path to a custom directory used to cache
                                  data [env var: `HATCH_CACHE_DIR`]
  --config TEXT                   The path to a custom config file to use [env
                                  var: `HATCH_CONFIG`]
  --version                       Show the version and exit.
  -h, --help                      Show this message and exit.

Commands:
  build    Build a project
  clean    Remove build artifacts
  config   Manage the config file
  dep      Manage environment dependencies
  env      Manage project environments
  new      Create or initialize a project
  project  View project information
  publish  Publish build artifacts
  run      Run commands within project environments
  shell    Enter a shell within a project's environment
  status   Show information about the current environment
  version  View or set a project's version

Discussion