サンプル
click 8.4.2: Define custom ParamType subclass to validate and convert custom argument types
検証済みサンプル — pypi click 8.4.2: Define custom ParamType subclass to validate and convert custom argument types. python 3.12 · linux alpine/x64 · docker で…
sha256:b4f195835771a8dae96255c220a4c0d80574d657c4ae2c2ef51e5462b09d92cb
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
MIT-0
実行証拠
宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。
- 証拠の基準
- 署名済みコントラクト合格
- 検証レシート
- 1
- ビルドした署名鍵
- 1
宣言された環境
linux 24 · ubuntu · glibc 2.39 x64 pip
検証実行環境
| 環境 | コントラクト | ステージ | 実行日 |
|---|---|---|---|
| python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962… |
2026-08-28 |
ケース
HOW- ゴール
- Define custom ParamType subclass to validate and convert custom argument types
- パッケージ
- シンボル
-
- click.ParamType
- click.ParamType.convert
- click.ParamType.fail
- click.ParamType.name
- 作成日
- 2026-08-28T04:13:15Z
コントラクト
- click.ParamType subclass defines name attribute for help synopsis
- convert() parses valid string arguments into custom Point coordinates
- convert() returns already instantiated Point objects without error
- invalid string formats call self.fail() which raises click.BadParameter and exits with code 2
- CliRunner captures parsed parameter values in command execution
ファイル
- NOTES.md
- PROMPT.md
- csx.json
- requirements.txt
- spec.json
- src/__init__.py
- src/cli.py
- test/contract.py
ソース
# Notes
### search_known_solution result
`search_known_solution` returned `NO_SAFE_MATCH` for defining a custom `ParamType` subclass with conversion and validation in Click.
### What a model would have written instead
Models often write raw Python conversion functions (`type=parse_func`) or fail to handle already converted default values inside `convert()`. When `convert()` encounters a default value that is already instantiated as the target object, omitting the `isinstance` guard causes unexpected `AttributeError` or `TypeError`. Furthermore, models often raise raw `ValueError` rather than calling `self.fail(message, param, ctx)`, which produces unhandled Python tracebacks (exit code 1) instead of Click's standard parameter usage error format (exit code 2).
### How the wrong version fails
1. Raising `ValueError` directly in `convert()` without `self.fail()` can bypass Click's structured parameter error attribution.
2. Failing to handle already-instantiated objects in `convert()` crashes whenever `default=Point(...)` is used.
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: Define custom ParamType subclass to validate and convert custom argument types
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:pypi/click@8.4.2
Demonstrate these symbols/APIs:
- click.ParamType
- click.ParamType.convert
- click.ParamType.fail
- click.ParamType.name
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:5e1c1c07d28288144c8fcc4e3affb7d79fc96875a218ceed681888dd4434db12","contract":["click.ParamType subclass defines name attribute for help synopsis","convert() parses valid string arguments into custom Point coordinates","convert() returns already instantiated Point objects without error","invalid string formats call self.fail() which raises click.BadParameter and exits with code 2","CliRunner captures parsed parameter values in command execution"],"goal":"Define custom ParamType subclass to validate and convert custom argument types","kind":"HOW","packages":["pkg:pypi/click@8.4.2"],"schemaVersion":1,"symbols":["click.ParamType","click.ParamType.convert","click.ParamType.fail","click.ParamType.name"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/click@8.4.2"],"schemaVersion":1,"subject":"pkg:pypi/click@8.4.2","symbols":["click.ParamType","click.ParamType.convert","click.ParamType.fail","click.ParamType.name"],"verifierAdapter":"python@1"}
click==8.4.2
{
"schemaVersion": 1,
"goal": "Define custom ParamType subclass to validate and convert custom argument types",
"kind": "HOW",
"packages": [
"pkg:pypi/click@8.4.2"
],
"symbols": [
"click.ParamType",
"click.ParamType.convert",
"click.ParamType.fail",
"click.ParamType.name"
]
}
"""Custom ParamType sample package."""
"""Custom click ParamType implementation and CLI."""
from typing import Any, Optional
import click
class Point(tuple):
"""2D Point coordinate (x, y)."""
def __new__(cls, x: int, y: int):
return super().__new__(cls, (x, y))
@property
def x(self) -> int:
return self[0]
@property
def y(self) -> int:
return self[1]
def __repr__(self) -> str:
return f"Point(x={self.x}, y={self.y})"
class PointParamType(click.ParamType):
"""Custom parameter type converting 'x,y' strings to Point(x, y)."""
name = "point"
def convert(
self,
value: Any,
param: Optional[click.Parameter],
ctx: Optional[click.Context],
) -> Point:
# Idempotence: if value is already a Point (e.g. from default), return directly
if isinstance(value, Point):
return value
if isinstance(value, tuple) and len(value) == 2 and all(isinstance(v, int) for v in value):
return Point(value[0], value[1])
if not isinstance(value, str):
self.fail(f"expected string or Point, got {type(value).__name__}", param, ctx)
parts = value.split(",")
if len(parts) != 2:
self.fail(f"expected 'x,y' format, got '{value}'", param, ctx)
try:
x = int(parts[0].strip())
y = int(parts[1].strip())
return Point(x, y)
except ValueError:
self.fail(f"coordinates must be integers, got '{value}'", param, ctx)
POINT = PointParamType()
@click.command()
@click.option(
"--origin",
type=POINT,
default=Point(0, 0),
help="Origin coordinate formatted as x,y",
)
@click.argument("target", type=POINT)
def translate(origin: Point, target: Point) -> None:
"""Translate from ORIGIN to TARGET point."""
dx = target.x - origin.x
dy = target.y - origin.y
click.echo(f"ORIGIN:{origin.x},{origin.y}")
click.echo(f"TARGET:{target.x},{target.y}")
click.echo(f"DELTA:{dx},{dy}")
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import click
from click.testing import CliRunner
from src.cli import POINT, Point, PointParamType, translate
runner = CliRunner()
# 1. Custom ParamType sets `name` attribute, which appears in help synopsis
assert POINT.name == "point"
help_res = runner.invoke(translate, ["--help"])
assert help_res.exit_code == 0
assert "POINT" in help_res.output or "point" in help_res.output.lower()
# 2. CLI arguments and options formatted as 'x,y' are parsed and converted to Point instances
res_valid = runner.invoke(translate, ["--origin", "10,20", "30,50"])
assert res_valid.exit_code == 0, res_valid.output
assert "ORIGIN:10,20" in res_valid.output
assert "TARGET:30,50" in res_valid.output
assert "DELTA:20,30" in res_valid.output
# 3. Default value passed as already-converted Point instance passes through without error
res_default = runner.invoke(translate, ["15,25"])
assert res_default.exit_code == 0, res_default.output
assert "ORIGIN:0,0" in res_default.output
assert "TARGET:15,25" in res_default.output
assert "DELTA:15,25" in res_default.output
# 4. Invalid input (wrong format or non-integer) calls self.fail() and exits with code 2 (usage error)
res_invalid_format = runner.invoke(translate, ["invalid_point"])
assert res_invalid_format.exit_code == 2, res_invalid_format.output
assert "expected 'x,y' format" in res_invalid_format.output
res_non_int = runner.invoke(translate, ["10,abc"])
assert res_non_int.exit_code == 2, res_non_int.output
assert "coordinates must be integers" in res_non_int.output
# 5. Direct convert() invocation converts strings and preserves already converted Point objects
pt = POINT.convert("100,200", None, None)
assert isinstance(pt, Point)
assert pt.x == 100 and pt.y == 200
pt_passthrough = POINT.convert(pt, None, None)
assert pt_passthrough is pt
# 6. Direct convert() on invalid input raises click.BadParameter via self.fail()
try:
POINT.convert("bad", None, None)
assert False, "convert() should have failed"
except click.BadParameter as e:
assert "expected 'x,y' format" in str(e)
print("CONTRACT PASS: click.ParamType custom type conversion and validation verified")
オリジンシーダー
匿名