CodeSampleX

サンプル

typing-extensions 4.16.0: verify TypeIs type narrowing predicate

検証済みサンプル — pypi typing-extensions 4.16.0: verify TypeIs type narrowing predicate. python 3.12 · linux alpine/x64 · docker で contract を実行し、成功しました.

sha256:e0eb80c00f4e79d6846249cb2367b7c53e72b89639d3f959a0e81d954b101566

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 python linux 24 · ubuntu · glibc 2.39 x64 python python 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-27

ケース

HOW
ゴール
verify pkg:pypi/typing-extensions@4.16.0 TypeIs type narrowing predicate
パッケージ
シンボル
  • typing_extensions.TypeIs
環境
python
作成日
2026-08-27T21:43:43Z

コントラクト

  1. TypeIs special form supports type subscripting and get_origin get_args introspection
  2. TypeIs return annotations are preserved by get_type_hints
  3. TypeIs predicate functions correctly distinguish target types from non-target types at runtime

ファイル

  • PROMPT.md
  • csx.json
  • requirements.txt
  • sample.py
  • spec.json
  • test/contract.py

ソースアーティファクトをダウンロード (tar.gz)

ソース

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: verify pkg:pypi/typing-extensions@4.16.0 TypeIs type narrowing predicate
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/typing-extensions@4.16.0
Demonstrate these symbols/APIs:
  - typing_extensions.TypeIs
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:6527d99032302c0242082de55728793ceaeeebd4ffe4c7dbd699b025980ecf4c","contract":["TypeIs special form supports type subscripting and get_origin get_args introspection","TypeIs return annotations are preserved by get_type_hints","TypeIs predicate functions correctly distinguish target types from non-target types at runtime"],"goal":"verify pkg:pypi/typing-extensions@4.16.0 TypeIs type narrowing predicate","kind":"HOW","packages":["pkg:pypi/typing-extensions@4.16.0"],"schemaVersion":1,"symbols":["typing_extensions.TypeIs"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/typing-extensions@4.16.0"],"schemaVersion":1,"subject":"pkg:pypi/typing-extensions@4.16.0","symbols":["typing_extensions.TypeIs"],"verifierAdapter":"python@1"}
requirements.txt
typing-extensions==4.16.0
sample.py
from typing import Any, List, Union
from typing_extensions import TypeIs, get_args, get_origin, get_type_hints


def is_string_list(val: object) -> TypeIs[List[str]]:
    """Check if val is a list where all elements are strings."""
    if not isinstance(val, list):
        return False
    return all(isinstance(x, str) for x in val)


def is_int_or_float(val: object) -> TypeIs[Union[int, float]]:
    """Check if val is numeric (int or float, excluding bool)."""
    if isinstance(val, bool):
        return False
    return isinstance(val, (int, float))


def filter_string_records(items: List[object]) -> List[List[str]]:
    """Filter out objects that are not string lists and return typed string lists."""
    results: List[List[str]] = []
    for item in items:
        if is_string_list(item):
            results.append(item)
    return results


def sum_numeric_values(items: List[object]) -> float:
    """Filter and sum all numeric values in a list."""
    total = 0.0
    for item in items:
        if is_int_or_float(item):
            total += float(item)
    return total


if __name__ == "__main__":
    test_data: List[object] = [
        ["alpha", "beta"],
        [1, 2, 3],
        "hello",
        ["gamma", "delta"],
        42,
    ]
    str_lists = filter_string_records(test_data)
    print(f"Extracted {len(str_lists)} string lists: {str_lists}")
    num_sum = sum_numeric_values(test_data)
    print(f"Sum of numeric elements: {num_sum}")
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:pypi/typing-extensions@4.16.0 TypeIs type narrowing predicate",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/typing-extensions@4.16.0"
  ],
  "symbols": [
    "typing_extensions.TypeIs"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.py
import os
import sys
from typing import List, Union

# Ensure project root is on sys.path for local module imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from typing_extensions import TypeIs, get_args, get_origin, get_type_hints
from sample import (
    filter_string_records,
    is_int_or_float,
    is_string_list,
    sum_numeric_values,
)


def test_typeis_special_form_introspection():
    # Assertion 1: TypeIs special form supports type subscripting and get_origin get_args introspection
    specialized = TypeIs[str]
    assert get_origin(specialized) is TypeIs, "Origin of TypeIs[str] must be TypeIs"
    assert get_args(specialized) == (str,), "Arguments of TypeIs[str] must be (str,)"

    nested = TypeIs[List[str]]
    assert get_origin(nested) is TypeIs, "Origin of TypeIs[List[str]] must be TypeIs"
    assert get_args(nested) == (List[str],), "Arguments of TypeIs[List[str]] must be (List[str],)"


def test_typeis_function_annotations():
    # Assertion 2: TypeIs return annotations are preserved by get_type_hints
    hints_str = get_type_hints(is_string_list)
    assert "return" in hints_str, "is_string_list must have a return type hint"
    assert get_origin(hints_str["return"]) is TypeIs, (
        "Return type hint origin must be TypeIs"
    )
    assert get_args(hints_str["return"]) == (List[str],), (
        "Return type hint argument must be List[str]"
    )

    hints_num = get_type_hints(is_int_or_float)
    assert get_origin(hints_num["return"]) is TypeIs, (
        "Return type hint origin must be TypeIs"
    )
    assert get_args(hints_num["return"]) == (Union[int, float],), (
        "Return type hint argument must be Union[int, float]"
    )


def test_typeis_runtime_predicates():
    # Assertion 3: TypeIs predicate functions correctly distinguish target types from non-target types at runtime
    # Positive assertions
    assert is_string_list(["apple", "banana"]) is True
    assert is_string_list([]) is True
    assert is_int_or_float(42) is True
    assert is_int_or_float(3.14) is True

    # Negative assertions
    assert is_string_list(["apple", 123]) is False
    assert is_string_list("not a list") is False
    assert is_string_list(None) is False
    assert is_string_list({"a": "b"}) is False
    assert is_int_or_float(True) is False  # bool is subclass of int in Python
    assert is_int_or_float("42") is False
    assert is_int_or_float(None) is False

    # Integrated execution test
    data: List[object] = [
        ["tag1", "tag2"],
        10,
        "string",
        ["tag3"],
        20.5,
        True,
        None,
        ["tag4", 99],
    ]
    filtered = filter_string_records(data)
    assert filtered == [["tag1", "tag2"], ["tag3"]], (
        f"Unexpected filtered output: {filtered}"
    )

    total = sum_numeric_values(data)
    assert total == 30.5, f"Expected 30.5, got {total}"


def main():
    test_typeis_special_form_introspection()
    test_typeis_function_annotations()
    test_typeis_runtime_predicates()
    print("Contract verification passed.")


if __name__ == "__main__":
    main()

オリジンシーダー

匿名