nikkie-ftnextの日記

イベントレポートや読書メモを発信

PEP 723をサポートしたツールがどんどん登場するので、私も独学目的で実装しました(バージョン 0.0.1公開!)

簡易版でお知らせします。
PEP 723(inline script metadata)のごくごく一部をサポートする実装をして、公開しました🎉

目次

PEP 723を実装しました!

% python -V
Python 3.12.6
% python -m venv .venv --upgrade-deps
% source .venv/bin/activate

inline script metadataの例のスクリプト
https://peps.python.org/pep-0723/#example
弊ツールが現在サポートしているのはdependenciesのみです

# /// script
# dependencies = [
#   "httpx",
#   "rich",
# ]
# ///

import httpx
from rich.pretty import pprint

resp = httpx.get("https://peps.python.org/api/peps.json")
data = resp.json()
pprint([(k, v["title"]) for k, v in data.items()][:5])

(.venv)が有効な状態で

% pip install pep723
% python -m pep723.tool example.py
[
│   ('1', 'PEP Purpose and Guidelines'),
│   ('2', 'Procedure for Adding New Modules'),
│   ('3', 'Guidelines for Handling Bug Reports'),
│   ('4', 'Deprecation of Standard Modules'),
│   ('5', 'Guidelines for Language Evolution')
]

metadataのdependenciesを見て、一時的な仮想環境に依存をインストールし、その仮想環境でスクリプトを実行します!
shirabeの経験が活きました1
実装の方向性としてはpip-runが近いと思います(ツール全体としてはpip-runの方が数段上手な実装です)。

実装してみて:metadataのパースはPEPより単純化できたみたい

PEP 723には参照実装があります。
https://peps.python.org/pep-0723/#reference-implementation

仕様上、metadataには空行(#だけの行)を持てるようなんですね2

# /// script
#
# dependencies = [
#   "httpx",
#   "rich",
# ]
#
# ///

PEPではこの空行も考慮して実装しているのですが

content = ''.join(
    line[2:] if line.startswith('# ') else line[1:]
    for line in matches[0].group('content').splitlines(keepends=True)
)
return tomllib.loads(content)

テストを書きながら実装したところ、'# 'で始まる行という判定は不要そうでした

content = "".join(
-    line[2:] if line.startswith('# ') else line[1:]
+    line[2:]
    for line in matches[0].group("content").splitlines(keepends=True)
)
return tomllib.loads(content)

#だけの行はline[1:]でもline[2:]でも空文字列となります

>>> "# dependencies = ["[2:]
'dependencies = ['
>>> "#"[2:]
''
>>> "#"[1:]
''

空文字列に代わりはないので、joinしてtomllibでloadsで読み込むときは、TOMLの空行扱い。
結果として同じならば、私としてはオッカムの剃刀3(≒前提が少ないほど好ましい)を信奉しており、条件式4A if cond else B)を使わずに書く方を採用しました✌️

ただし、オススメはこちらのツール

私のは独学目的なので(まだ使わないでください
以下からお好きなものをどうぞ

  • pipx
  • uv
  • Hatch
  • PDM

inline script metadataサポートまわりの実装を見た5感覚から、いまの私が人におすすめするならuvかHatchです。
2つから選ぶのは採用したい文脈に依存するので、個別にお話しお聞かせください。

どんどんサポートしている様子


  1. otherwise just the first character (which means the line consists of only a single #).」ref: https://peps.python.org/pep-0723/#specification
  2. 過去に取り上げたブログ
  3. 三項演算子とも呼ばれます