Ejemplo
typing-extensions 4.16.0: typing_extensions.Literal
Muestra verificada para pypi typing-extensions 4.16.0: typing_extensions.Literal. El contrato se ejecutó en python 3.12 · linux debian/x64 · docker y pasó.
sha256:5b0abc40a34f72f7d53da828f7621d126dfbf58a8cd6d0964dc9b621e6e992dd
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
linux 24 · ubuntu · glibc 2.39 x64 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-06 |
Caso
HOW- Objetivo
- verify typing_extensions.Literal in pkg:pypi/typing-extensions@4.16.0
- Paquetes
- Símbolos
-
- typing_extensions.Literal
- Creado
- 2026-09-06T01:32:37Z
Contrato
- typing_extensions.Literal defines types constrained to specific literal values inspectable via get_args and get_origin
- typing_extensions.Literal flattens nested Literal definitions and deduplicates identical literal arguments regardless of order
- typing_extensions.Literal distinguishes boolean values from integer values such that Literal[True] is not equal to Literal[1]
- typing_extensions.Literal disallows direct instantiation and raises TypeError when evaluated with isinstance
- typing_extensions.Literal supports runtime validation and membership checking across strings, numbers, booleans, and None
Archivos
- PROMPT.md
- csx.json
- requirements.txt
- sample.py
- spec.json
- test/contract.py
Código fuente
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.Literal 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.Literal
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:28e61a8028c0e59bf25dbd218ef7a77e1463c042d15a366c14fd2c739b7ad582","contract":["typing_extensions.Literal defines types constrained to specific literal values inspectable via get_args and get_origin","typing_extensions.Literal flattens nested Literal definitions and deduplicates identical literal arguments regardless of order","typing_extensions.Literal distinguishes boolean values from integer values such that Literal[True] is not equal to Literal[1]","typing_extensions.Literal disallows direct instantiation and raises TypeError when evaluated with isinstance","typing_extensions.Literal supports runtime validation and membership checking across strings, numbers, booleans, and None"],"goal":"verify typing_extensions.Literal in pkg:pypi/typing-extensions@4.16.0","kind":"HOW","packages":["pkg:pypi/typing-extensions@4.16.0"],"schemaVersion":1,"symbols":["typing_extensions.Literal"]},"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/typing-extensions@4.16.0"],"schemaVersion":1,"subject":"pkg:pypi/typing-extensions@4.16.0","symbols":["typing_extensions.Literal"],"verifierAdapter":"python@1"}
typing-extensions==4.16.0
"""Demonstration of typing_extensions.Literal for compile-time and runtime type constraints."""
from typing import Any, Dict, Tuple
from typing_extensions import Literal, get_args, get_origin
# Type definitions demonstrating various Literal usages
HTTPMethod = Literal["GET", "POST", "PUT", "DELETE"]
RetryCount = Literal[0, 1, 2, 3]
ToggleState = Literal[True, False]
StatusResponse = Literal["ok", "error", 200, 404, None]
# Nested and composite literals
ReadMode = Literal["r", "rb"]
WriteMode = Literal["w", "wb"]
FileMode = Literal[ReadMode, WriteMode, "a", "ab"]
def get_literal_candidates(literal_type: Any) -> Tuple[Any, ...]:
"""Return the allowed values defined within a Literal type annotation.
Raises:
TypeError: If the provided type is not a Literal.
"""
origin = get_origin(literal_type)
if origin is not Literal and str(origin) not in ("typing.Literal", "typing_extensions.Literal"):
raise TypeError(f"{literal_type} is not a Literal type")
return get_args(literal_type)
def is_literal_value(value: Any, literal_type: Any) -> bool:
"""Check if value matches any candidate in the literal type.
Distinguishes types strictly so boolean values (True/False) do not match
integer values (1/0), adhering to the Literal specification.
"""
candidates = get_literal_candidates(literal_type)
for candidate in candidates:
if type(candidate) is type(value) and candidate == value:
return True
return False
def validate_literal_value(value: Any, literal_type: Any) -> Any:
"""Validate that value satisfies the literal constraint, returning the value or raising ValueError."""
if not is_literal_value(value, literal_type):
allowed = get_literal_candidates(literal_type)
raise ValueError(f"Invalid value {value!r}. Expected one of: {allowed!r}")
return value
def configure_endpoint(method: HTTPMethod, retries: RetryCount = 0) -> Dict[str, Any]:
"""Configure an endpoint action with strictly validated HTTP method and retry count."""
validated_method = validate_literal_value(method, HTTPMethod)
validated_retries = validate_literal_value(retries, RetryCount)
return {
"method": validated_method,
"retries": validated_retries,
}
def open_file_handle(mode: FileMode) -> str:
"""Validate file access mode against nested Literal definition."""
validated_mode = validate_literal_value(mode, FileMode)
return f"handle opened in mode '{validated_mode}'"
{
"schemaVersion": 1,
"goal": "verify typing_extensions.Literal in pkg:pypi/typing-extensions@4.16.0",
"kind": "HOW",
"packages": [
"pkg:pypi/typing-extensions@4.16.0"
],
"symbols": [
"typing_extensions.Literal"
]
}
"""Contract verification tests for typing_extensions.Literal."""
import os
import sys
# Ensure sample root directory is in sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from typing_extensions import Literal, get_args, get_origin
import sample
def test_literal_definition_and_introspection() -> None:
"""Assertion 1: typing_extensions.Literal defines types constrained to specific literal values inspectable via get_args and get_origin."""
origin = get_origin(sample.HTTPMethod)
assert origin is Literal or str(origin) in ("typing.Literal", "typing_extensions.Literal"), (
f"Expected origin to be Literal, got {origin}"
)
args = get_args(sample.HTTPMethod)
assert args == ("GET", "POST", "PUT", "DELETE"), f"Unexpected args: {args}"
candidates = sample.get_literal_candidates(sample.RetryCount)
assert candidates == (0, 1, 2, 3), f"Unexpected candidates: {candidates}"
# Non-literal raises TypeError in get_literal_candidates
try:
sample.get_literal_candidates(int)
assert False, "Expected TypeError for non-Literal type"
except TypeError:
pass
def test_literal_flattening_and_deduplication() -> None:
"""Assertion 2: typing_extensions.Literal flattens nested Literal definitions and deduplicates identical literal arguments regardless of order."""
# Nested Literal types are automatically flattened
assert sample.FileMode == Literal["r", "rb", "w", "wb", "a", "ab"], (
"Nested FileMode did not flatten as expected"
)
# Nesting and duplicates
combined = Literal[Literal[1, 2], Literal[2, 3], 1]
assert combined == Literal[1, 2, 3], f"Flattening/deduplication mismatch: {combined}"
# Order independence for type equivalence
assert Literal["alpha", "beta"] == Literal["beta", "alpha"], (
"Literal types with identical arguments in different order should be equivalent"
)
def test_literal_bool_and_int_distinction() -> None:
"""Assertion 3: typing_extensions.Literal distinguishes boolean values from integer values such that Literal[True] is not equal to Literal[1]."""
# PEP 586 requires distinguishing bool from int even though True == 1 in Python
assert Literal[True] != Literal[1], "Literal[True] must not equal Literal[1]"
assert Literal[False] != Literal[0], "Literal[False] must not equal Literal[0]"
mixed = Literal[1, True]
assert get_args(mixed) == (1, True), f"Expected both 1 and True to be preserved, got {get_args(mixed)}"
# Check strict runtime matching
assert sample.is_literal_value(True, Literal[True]) is True
assert sample.is_literal_value(1, Literal[True]) is False
assert sample.is_literal_value(True, Literal[1]) is False
assert sample.is_literal_value(1, Literal[1]) is True
def test_literal_instantiation_and_isinstance_prohibitions() -> None:
"""Assertion 4: typing_extensions.Literal disallows direct instantiation and raises TypeError when evaluated with isinstance."""
# Direct instantiation is prohibited
try:
Literal()
assert False, "Direct instantiation of Literal should raise TypeError"
except TypeError as exc:
assert isinstance(exc, TypeError)
# isinstance check with subscripted Literal is prohibited
try:
isinstance("GET", sample.HTTPMethod)
assert False, "isinstance with Literal should raise TypeError"
except TypeError as exc:
assert isinstance(exc, TypeError)
try:
isinstance(0, sample.RetryCount)
assert False, "isinstance with RetryCount should raise TypeError"
except TypeError as exc:
assert isinstance(exc, TypeError)
def test_literal_runtime_validation() -> None:
"""Assertion 5: typing_extensions.Literal supports runtime validation and membership checking across strings, numbers, booleans, and None."""
# Validations succeed
assert sample.validate_literal_value("GET", sample.HTTPMethod) == "GET"
assert sample.validate_literal_value(2, sample.RetryCount) == 2
assert sample.validate_literal_value(None, sample.StatusResponse) is None
assert sample.validate_literal_value(404, sample.StatusResponse) == 404
assert sample.validate_literal_value(True, sample.ToggleState) is True
# Higher-level function calls succeed
endpoint = sample.configure_endpoint("POST", 3)
assert endpoint == {"method": "POST", "retries": 3}
file_msg = sample.open_file_handle("rb")
assert file_msg == "handle opened in mode 'rb'"
# Invalid values raise ValueError
try:
sample.validate_literal_value("OPTIONS", sample.HTTPMethod)
assert False, "Expected ValueError for invalid HTTP method"
except ValueError:
pass
try:
sample.validate_literal_value(99, sample.RetryCount)
assert False, "Expected ValueError for invalid retry count"
except ValueError:
pass
def main() -> None:
test_literal_definition_and_introspection()
test_literal_flattening_and_deduplication()
test_literal_bool_and_int_distinction()
test_literal_instantiation_and_isinstance_prohibitions()
test_literal_runtime_validation()
print("All typing_extensions.Literal contract assertions passed successfully.")
if __name__ == "__main__":
main()
Seeder de origen
anónimo