CodeSampleX

Exemple

exceptiongroup 1.3.1: ExceptionGroup, catch

Échantillon vérifié pour pypi exceptiongroup 1.3.1: ExceptionGroup, catch. Le contrat s'est exécuté sur python 3.12 · linux alpine/x64 · docker et a réussi.

sha256:382a9b8a753350cb9c8f9729209524047e1c2a897d2c14913c4483ccd1903251

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré python linux 24 · ubuntu · glibc 2.39 x64 python python pip

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-20

Cas

HOW
Objectif
verify pkg:pypi/exceptiongroup@1.3.1
Paquets
Symboles
  • exceptiongroup.ExceptionGroup
  • exceptiongroup.catch
Environnement
python
Créé
2026-08-20T12:53:49Z

Contrat

  1. exceptiongroup.ExceptionGroup aggregates multiple exceptions and supports filtering via subgroup and split
  2. exceptiongroup.catch handles matched exception types from ExceptionGroup and raises unhandled exceptions

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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/exceptiongroup@1.3.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/exceptiongroup@1.3.1
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:d192d164c4d0b5bf9593645232b68bc47a0fd6ed81c982ec4adc8dae3f8aa087","contract":["exceptiongroup.ExceptionGroup aggregates multiple exceptions and supports filtering via subgroup and split","exceptiongroup.catch handles matched exception types from ExceptionGroup and raises unhandled exceptions"],"goal":"verify pkg:pypi/exceptiongroup@1.3.1","kind":"HOW","packages":["pkg:pypi/exceptiongroup@1.3.1"],"schemaVersion":1,"symbols":["exceptiongroup.ExceptionGroup","exceptiongroup.catch"]},"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/exceptiongroup@1.3.1"],"schemaVersion":1,"symbols":["exceptiongroup.ExceptionGroup","exceptiongroup.catch"],"verifierAdapter":"python@1"}
requirements.txt
exceptiongroup==1.3.1
typing-extensions==4.12.2
sample.py
"""Sample demonstrating ExceptionGroup creation, filtering, and catch context handling."""

from typing import Callable, List, Optional, Tuple, Type
from exceptiongroup import ExceptionGroup, catch


def create_error_group(
    message: str, errors: List[Exception]
) -> ExceptionGroup:
    """Create an ExceptionGroup aggregating multiple exceptions."""
    return ExceptionGroup(message, errors)


def partition_errors(
    group: ExceptionGroup, predicate: Callable[[Exception], bool]
) -> Tuple[Optional[ExceptionGroup], Optional[ExceptionGroup]]:
    """Partition an ExceptionGroup into matching and non-matching subgroups using split."""
    match_group, rest_group = group.split(predicate)
    return match_group, rest_group


def filter_errors(
    group: ExceptionGroup, predicate: Callable[[Exception], bool]
) -> Optional[ExceptionGroup]:
    """Filter an ExceptionGroup to obtain only matching exceptions using subgroup."""
    return group.subgroup(predicate)


def execute_with_error_handling(
    task: Callable[[], None],
    handlers: dict[Type[Exception], Callable[[Exception], None]],
) -> None:
    """Execute a task with exceptiongroup.catch to handle specific exception types."""
    with catch(handlers):
        task()
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:pypi/exceptiongroup@1.3.1",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/exceptiongroup@1.3.1"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.py
"""Contract verification test for exceptiongroup."""

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 exceptiongroup import ExceptionGroup, catch
from sample import (
    create_error_group,
    filter_errors,
    partition_errors,
    execute_with_error_handling,
)


def test_exceptiongroup_aggregation_and_filtering() -> None:
    """Assertion 1: exceptiongroup.ExceptionGroup aggregates multiple exceptions and supports filtering via subgroup and split."""
    err1 = ValueError("invalid value 1")
    err2 = TypeError("invalid type")
    err3 = ValueError("invalid value 2")
    err4 = KeyError("missing key")

    group = create_error_group("batch operation failed", [err1, err2, err3, err4])

    assert group.message == "batch operation failed"
    assert len(group.exceptions) == 4
    assert group.exceptions == (err1, err2, err3, err4)

    # Test subgroup
    value_errors_group = filter_errors(group, lambda exc: isinstance(exc, ValueError))
    assert value_errors_group is not None
    assert len(value_errors_group.exceptions) == 2
    assert value_errors_group.exceptions == (err1, err3)

    no_match_group = filter_errors(group, lambda exc: isinstance(exc, IndexError))
    assert no_match_group is None

    # Test split
    matched_type, rest_type = partition_errors(group, lambda exc: isinstance(exc, TypeError))
    assert matched_type is not None
    assert len(matched_type.exceptions) == 1
    assert matched_type.exceptions == (err2,)

    assert rest_type is not None
    assert len(rest_type.exceptions) == 3
    assert rest_type.exceptions == (err1, err3, err4)


def test_catch_context_manager() -> None:
    """Assertion 2: exceptiongroup.catch handles matched exception types from ExceptionGroup and raises unhandled exceptions."""
    handled_value_errors = []
    handled_type_errors = []

    def handle_value(exc: Exception) -> None:
        handled_value_errors.append(exc)

    def handle_type(exc: Exception) -> None:
        handled_type_errors.append(exc)

    # Scenario 1: All exceptions in the group are handled
    def failing_batch_all_handled() -> None:
        raise ExceptionGroup(
            "all handled errors",
            [ValueError("val err"), TypeError("type err")],
        )

    execute_with_error_handling(
        failing_batch_all_handled,
        {ValueError: handle_value, TypeError: handle_type},
    )

    assert len(handled_value_errors) == 1
    assert len(handled_type_errors) == 1

    # Scenario 2: Unhandled exceptions are re-raised in a new ExceptionGroup
    unhandled_raised = False

    def failing_batch_partial_handled() -> None:
        raise ExceptionGroup(
            "partial errors",
            [ValueError("handled val"), KeyError("unhandled key")],
        )

    try:
        execute_with_error_handling(
            failing_batch_partial_handled,
            {ValueError: handle_value},
        )
    except ExceptionGroup as eg:
        unhandled_raised = True
        assert len(eg.exceptions) == 1
        assert isinstance(eg.exceptions[0], KeyError)

    assert unhandled_raised is True
    assert len(handled_value_errors) == 2


def main() -> None:
    test_exceptiongroup_aggregation_and_filtering()
    test_catch_context_manager()
    print("Contract verification passed successfully.")


if __name__ == "__main__":
    main()

Seeder d'origine

anonyme