示例
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. contract 在 python 3.12 · linux alpine/x64 · docker…
sha256:b4f195835771a8dae96255c220a4c0d80574d657c4ae2c2ef51e5462b09d92cb
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
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")
原始种子者
匿名