CodeSampleX

샘플

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

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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

컨트랙트

  1. click.ParamType subclass defines name attribute for help synopsis
  2. convert() parses valid string arguments into custom Point coordinates
  3. convert() returns already instantiated Point objects without error
  4. invalid string formats call self.fail() which raises click.BadParameter and exits with code 2
  5. 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

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# 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.
PROMPT.md
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.
csx.json
{"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"}
requirements.txt
click==8.4.2
spec.json
{
  "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"
  ]
}
src/__init__.py
"""Custom ParamType sample package."""
src/cli.py
"""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}")
test/contract.py
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")

오리진 시더

익명