CodeSampleX

Ejemplo

typing-extensions 4.16.0: typing_extensions.Annotated

Muestra verificada para pypi typing-extensions 4.16.0: typing_extensions.Annotated. El contrato se ejecutó en python 3.12 · linux debian/x64 · docker y pasó.

sha256:6a0e909d8511dcfd76391c629a89b645b4a93d056c2e8c75ce8e0ded7958dc53

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado python linux 24 · ubuntu · glibc 2.39 x64 python python pip

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
verify typing_extensions.Annotated in pkg:pypi/typing-extensions@4.16.0
Paquetes
Símbolos
  • typing_extensions.Annotated
Entorno
python
Creado
2026-09-05T22:51:53Z

Contrato

  1. Annotated attaches arbitrary runtime metadata to a type and provides get_origin and get_args introspection
  2. Annotated flattens nested annotations preserving argument ordering while maintaining equality semantics
  3. typing_extensions get_type_hints unwraps or preserves Annotated metadata based on the include_extras flag
  4. Annotated requires at least two arguments raising TypeError when parameterized with fewer arguments

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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.Annotated 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.Annotated

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:190c224c634b1557bad871d93e95451ccd23881ad3a5fd69fb1fc976607597e3","contract":["Annotated attaches arbitrary runtime metadata to a type and provides get_origin and get_args introspection","Annotated flattens nested annotations preserving argument ordering while maintaining equality semantics","typing_extensions get_type_hints unwraps or preserves Annotated metadata based on the include_extras flag","Annotated requires at least two arguments raising TypeError when parameterized with fewer arguments"],"goal":"verify typing_extensions.Annotated in pkg:pypi/typing-extensions@4.16.0","kind":"HOW","packages":["pkg:pypi/typing-extensions@4.16.0"],"schemaVersion":1,"symbols":["typing_extensions.Annotated"]},"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.Annotated"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-typing-extensions-annotated"
version = "0.1.0"
dependencies = [
    "typing-extensions==4.16.0",
]
requirements.txt
typing-extensions==4.16.0
sample.py
"""Demonstration of type annotation metadata using typing_extensions.Annotated."""

from typing import Any, Tuple
from typing_extensions import Annotated, get_args, get_origin


class ValueRange:
    """Metadata constraint specifying minimum and maximum allowable values."""

    def __init__(self, min_val: int, max_val: int) -> None:
        self.min_val = min_val
        self.max_val = max_val

    def validate(self, value: int) -> bool:
        return self.min_val <= value <= self.max_val

    def __repr__(self) -> str:
        return f"ValueRange({self.min_val}, {self.max_val})"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, ValueRange):
            return False
        return self.min_val == other.min_val and self.max_val == other.max_val


# Type aliases using Annotated
PortNumber = Annotated[int, ValueRange(1, 65535), "Network port number"]
PositiveInt = Annotated[int, ValueRange(1, 2147483647)]


def extract_metadata(annotated_type: Any) -> Tuple[Any, ...]:
    """Extract metadata elements attached to an Annotated type."""
    if get_origin(annotated_type) is not Annotated:
        return ()
    args = get_args(annotated_type)
    return args[1:]


def extract_underlying_type(annotated_type: Any) -> Any:
    """Extract the underlying data type from an Annotated type."""
    if get_origin(annotated_type) is not Annotated:
        return annotated_type
    args = get_args(annotated_type)
    return args[0]


def validate_annotated_value(annotated_type: Any, value: Any) -> bool:
    """Validate a value against any ValueRange constraints in Annotated metadata."""
    underlying = extract_underlying_type(annotated_type)
    if not isinstance(value, underlying):
        return False

    for item in extract_metadata(annotated_type):
        if isinstance(item, ValueRange) and not item.validate(value):
            return False
    return True


def format_service_endpoint(
    host: Annotated[str, "Hostname or IP address"],
    port: PortNumber,
) -> Annotated[str, "Formatted endpoint URL"]:
    """Format host and port into an endpoint string."""
    return f"{host}:{port}"
spec.json
{
  "schemaVersion": 1,
  "goal": "verify typing_extensions.Annotated in pkg:pypi/typing-extensions@4.16.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/typing-extensions@4.16.0"
  ],
  "symbols": [
    "typing_extensions.Annotated"
  ]
}
test/contract.py
"""Contract verification test for typing_extensions.Annotated 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 Annotated, get_args, get_origin, get_type_hints
from sample import (
    PortNumber,
    PositiveInt,
    ValueRange,
    extract_metadata,
    extract_underlying_type,
    format_service_endpoint,
    validate_annotated_value,
)


def test_annotated_metadata_and_introspection() -> None:
    """Assertion 1: Annotated attaches arbitrary runtime metadata to a type and provides get_origin and get_args introspection."""
    annotated_type = Annotated[int, "description", 42]

    # get_origin and get_args introspection
    assert get_origin(annotated_type) is Annotated, "Origin must be Annotated"
    assert get_args(annotated_type) == (int, "description", 42), "Args must match type and metadata"

    # Helper function checks
    assert extract_underlying_type(annotated_type) is int
    assert extract_metadata(annotated_type) == ("description", 42)

    # PortNumber alias check
    assert get_origin(PortNumber) is Annotated
    assert extract_underlying_type(PortNumber) is int
    metadata = extract_metadata(PortNumber)
    assert len(metadata) == 2
    assert metadata[0] == ValueRange(1, 65535)
    assert metadata[1] == "Network port number"

    # Non-annotated types return empty metadata and original type
    assert extract_metadata(int) == ()
    assert extract_underlying_type(int) is int


def test_annotated_flattening_and_equality() -> None:
    """Assertion 2: Annotated flattens nested annotations preserving argument ordering while maintaining equality semantics."""
    inner = Annotated[int, "first", 1]
    nested = Annotated[inner, "second", 2]

    # Nesting Annotated flattens the metadata
    assert get_origin(nested) is Annotated
    assert get_args(nested) == (int, "first", 1, "second", 2)
    assert extract_metadata(nested) == ("first", 1, "second", 2)

    # Equality semantics
    same_type_a = Annotated[str, "tag", 100]
    same_type_b = Annotated[str, "tag", 100]
    different_meta = Annotated[str, "tag", 200]
    different_type = Annotated[int, "tag", 100]

    assert same_type_a == same_type_b
    assert same_type_a != different_meta
    assert same_type_a != different_type
    assert same_type_a != str


def test_type_hints_with_include_extras() -> None:
    """Assertion 3: typing_extensions get_type_hints unwraps or preserves Annotated metadata based on the include_extras flag."""
    hints_full = get_type_hints(format_service_endpoint, include_extras=True)
    hints_stripped = get_type_hints(format_service_endpoint, include_extras=False)

    # With include_extras=True, Annotated types are preserved
    assert get_origin(hints_full["host"]) is Annotated
    assert get_args(hints_full["host"]) == (str, "Hostname or IP address")
    assert get_origin(hints_full["port"]) is Annotated
    assert get_args(hints_full["port"])[0] is int
    assert get_origin(hints_full["return"]) is Annotated

    # With include_extras=False, metadata is stripped down to underlying types
    assert hints_stripped["host"] is str
    assert hints_stripped["port"] is int
    assert hints_stripped["return"] is str


def test_annotated_argument_count_validation() -> None:
    """Assertion 4: Annotated requires at least two arguments raising TypeError when parameterized with fewer arguments."""
    type_error_raised = False
    try:
        Annotated[int]
    except TypeError as exc:
        type_error_raised = True
        assert "at least two arguments" in str(exc)

    assert type_error_raised, "Annotated[int] must raise TypeError"

    # Runtime validation using sample helper
    assert validate_annotated_value(PortNumber, 8080) is True
    assert validate_annotated_value(PortNumber, 80) is True
    assert validate_annotated_value(PortNumber, 70000) is False
    assert validate_annotated_value(PortNumber, -1) is False
    assert validate_annotated_value(PortNumber, "8080") is False


def main() -> None:
    test_annotated_metadata_and_introspection()
    test_annotated_flattening_and_equality()
    test_type_hints_with_include_extras()
    test_annotated_argument_count_validation()
    print("All contract assertions passed.")


if __name__ == "__main__":
    main()

Seeder de origen

anónimo