CodeSampleX

サンプル

typing-extensions 4.16.0: typing_extensions.Generic

検証済みサンプル — pypi typing-extensions 4.16.0: typing_extensions.Generic. python 3.12 · linux debian/x64 · docker で contract を実行し、成功しました.

sha256:aaad555d4646518f15f4b3c23bad0673a2eaa1a428b33a1bc44824cda06d3b58

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

実行証拠

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

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

検証実行環境

環境 コントラクト ステージ 実行日
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-05

ケース

HOW
ゴール
verify typing_extensions.Generic in pkg:pypi/typing-extensions@4.16.0
パッケージ
シンボル
  • typing_extensions.Generic
環境
python
作成日
2026-09-05T23:04:50Z

コントラクト

  1. Generic creates parameterized generic classes with TypeVar parameters that populate __parameters__
  2. Subscripting a Generic subclass binds type arguments and preserves original class as origin
  3. Subscripting a Generic subclass with incorrect parameter count raises TypeError
  4. Inheriting directly from unparameterized Generic or parameterizing Generic with non-typevars raises TypeError
  5. Subscripted Generic types reject isinstance and issubclass checks with TypeError
  6. Generic subclasses support partial and complete type parameter specialization

ファイル

  • PROMPT.md
  • csx.json
  • pyproject.toml
  • 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 typing_extensions.Generic in pkg:pypi/typing-extensions@4.16.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/typing-extensions@4.16.0
Demonstrate these symbols/APIs:
  - typing_extensions.Generic

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:128f6f9d4aabdc596f5b46ca6ea7eeeb3b2657fe3e6c673cad654e78b7d6b59d","contract":["Generic creates parameterized generic classes with TypeVar parameters that populate __parameters__","Subscripting a Generic subclass binds type arguments and preserves original class as origin","Subscripting a Generic subclass with incorrect parameter count raises TypeError","Inheriting directly from unparameterized Generic or parameterizing Generic with non-typevars raises TypeError","Subscripted Generic types reject isinstance and issubclass checks with TypeError","Generic subclasses support partial and complete type parameter specialization"],"goal":"verify typing_extensions.Generic in pkg:pypi/typing-extensions@4.16.0","kind":"HOW","packages":["pkg:pypi/typing-extensions@4.16.0"],"schemaVersion":1,"symbols":["typing_extensions.Generic"]},"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.Generic"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-typing-extensions-generic"
version = "0.1.0"
dependencies = [
    "typing-extensions==4.16.0",
]
requirements.txt
typing-extensions==4.16.0
sample.py
"""Demonstration of generic classes using typing_extensions.Generic."""

from typing import Any, List, Optional, Tuple, TypeVar
from typing_extensions import Generic, get_args, get_origin

T = TypeVar("T")
K = TypeVar("K")
V = TypeVar("V")


class Stack(Generic[T]):
    """Generic LIFO stack with a single type parameter."""

    def __init__(self) -> None:
        self.items: List[T] = []

    def push(self, item: T) -> None:
        self.items.append(item)

    def pop(self) -> T:
        if not self.items:
            raise IndexError("pop from empty stack")
        return self.items.pop()

    def peek(self) -> Optional[T]:
        return self.items[-1] if self.items else None

    def __len__(self) -> int:
        return len(self.items)


class KeyValueStore(Generic[K, V]):
    """Generic key-value storage with two type parameters."""

    def __init__(self) -> None:
        self._entries: dict[K, V] = {}

    def put(self, key: K, value: V) -> None:
        self._entries[key] = value

    def get(self, key: K) -> Optional[V]:
        return self._entries.get(key)

    def contains(self, key: K) -> bool:
        return key in self._entries


class StringKeyStore(KeyValueStore[str, V]):
    """Partially specialized Generic subclass where key is fixed to str."""


class ConfigurationMap(KeyValueStore[str, int]):
    """Fully specialized Generic subclass where key is str and value is int."""


def inspect_parameters(generic_cls: Any) -> Tuple[Any, ...]:
    """Return type parameters of a Generic class."""
    return getattr(generic_cls, "__parameters__", ())


def inspect_origin_and_args(specialized_type: Any) -> Tuple[Any, Tuple[Any, ...]]:
    """Return the origin class and type arguments of a parameterized type."""
    return get_origin(specialized_type), get_args(specialized_type)
spec.json
{
  "schemaVersion": 1,
  "goal": "verify typing_extensions.Generic in pkg:pypi/typing-extensions@4.16.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/typing-extensions@4.16.0"
  ],
  "symbols": [
    "typing_extensions.Generic"
  ]
}
test/contract.py
"""Contract verification test for typing_extensions.Generic in pkg:pypi/typing-extensions@4.16.0."""

import os
import sys

# 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 Generic, get_args, get_origin
from sample import (
    ConfigurationMap,
    KeyValueStore,
    Stack,
    StringKeyStore,
    inspect_origin_and_args,
    inspect_parameters,
)


def test_generic_parameters() -> None:
    """Assertion 1: Generic creates parameterized generic classes with TypeVar parameters that populate __parameters__."""
    assert len(Stack.__parameters__) == 1
    assert Stack.__parameters__[0].__name__ == "T"

    assert len(KeyValueStore.__parameters__) == 2
    param_names = tuple(p.__name__ for p in KeyValueStore.__parameters__)
    assert param_names == ("K", "V")

    # Helper function verification
    assert inspect_parameters(Stack) == Stack.__parameters__
    assert inspect_parameters(KeyValueStore) == KeyValueStore.__parameters__


def test_subscripting_and_origin() -> None:
    """Assertion 2: Subscripting a Generic subclass binds type arguments and preserves original class as origin."""
    int_stack = Stack[int]
    assert get_origin(int_stack) is Stack
    assert get_args(int_stack) == (int,)

    origin, args = inspect_origin_and_args(int_stack)
    assert origin is Stack
    assert args == (int,)

    str_float_store = KeyValueStore[str, float]
    assert get_origin(str_float_store) is KeyValueStore
    assert get_args(str_float_store) == (str, float)

    origin_kv, args_kv = inspect_origin_and_args(str_float_store)
    assert origin_kv is KeyValueStore
    assert args_kv == (str, float)


def test_mismatched_parameter_count_raises_type_error() -> None:
    """Assertion 3: Subscripting a Generic subclass with incorrect parameter count raises TypeError."""
    try:
        Stack[int, str]  # type: ignore[misc]
        raise AssertionError("Expected TypeError when passing too many type arguments to Stack")
    except TypeError:
        pass

    try:
        KeyValueStore[int]  # type: ignore[misc]
        raise AssertionError("Expected TypeError when passing too few type arguments to KeyValueStore")
    except TypeError:
        pass

    try:
        KeyValueStore[int, str, float]  # type: ignore[misc]
        raise AssertionError("Expected TypeError when passing too many type arguments to KeyValueStore")
    except TypeError:
        pass


def test_invalid_generic_usage_raises_type_error() -> None:
    """Assertion 4: Inheriting directly from unparameterized Generic or parameterizing Generic with non-typevars raises TypeError."""
    try:
        class UnparameterizedInheritance(Generic):  # type: ignore[misc]
            pass

        raise AssertionError("Expected TypeError when inheriting from unparameterized Generic")
    except TypeError:
        pass

    try:
        Generic[int]  # type: ignore[misc]
        raise AssertionError("Expected TypeError when subscripting Generic with concrete type int")
    except TypeError:
        pass


def test_subscripted_generic_rejects_instance_checks() -> None:
    """Assertion 5: Subscripted Generic types reject isinstance and issubclass checks with TypeError."""
    stack_instance = Stack[int]()
    stack_instance.push(42)
    assert stack_instance.pop() == 42

    # isinstance on unparameterized Generic class succeeds
    assert isinstance(stack_instance, Stack)

    # isinstance on subscripted Generic type raises TypeError
    try:
        isinstance(stack_instance, Stack[int])
        raise AssertionError("Expected TypeError on isinstance(stack_instance, Stack[int])")
    except TypeError:
        pass

    # issubclass on subscripted Generic type raises TypeError
    try:
        issubclass(Stack, Stack[int])
        raise AssertionError("Expected TypeError on issubclass(Stack, Stack[int])")
    except TypeError:
        pass


def test_specialization_subclasses() -> None:
    """Assertion 6: Generic subclasses support partial and complete type parameter specialization."""
    # Partial specialization: StringKeyStore retains 1 type parameter (V)
    assert len(StringKeyStore.__parameters__) == 1
    assert StringKeyStore.__parameters__[0].__name__ == "V"

    str_int_store = StringKeyStore[int]()
    str_int_store.put("cache_size", 1024)
    assert str_int_store.get("cache_size") == 1024
    assert str_int_store.contains("cache_size") is True
    assert str_int_store.contains("missing") is False

    # Full specialization: ConfigurationMap has 0 type parameters left
    assert ConfigurationMap.__parameters__ == ()

    config = ConfigurationMap()
    config.put("timeout_seconds", 60)
    assert config.get("timeout_seconds") == 60
    assert config.get("unknown_key") is None
    assert isinstance(config, KeyValueStore)


def main() -> None:
    test_generic_parameters()
    test_subscripting_and_origin()
    test_mismatched_parameter_count_raises_type_error()
    test_invalid_generic_usage_raises_type_error()
    test_subscripted_generic_rejects_instance_checks()
    test_specialization_subclasses()
    print("All contract assertions passed.")


if __name__ == "__main__":
    main()

オリジンシーダー

匿名