CodeSampleX

Exemplo

pyyaml 6.0.3: safe YAML parsing, custom dumping, and safe_load with PyYAML

Amostra verificada para pypi pyyaml 6.0.3: safe YAML parsing, custom dumping, and safe_load with PyYAML. O contrato rodou em python 3.12 · linux alpine/x64 …

sha256:f33b03c1fbf97dc469bbba37b68bc06aba094a2206d9f39056a821a0f1d6c247

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado python linux 24 · ubuntu · glibc 2.39 x64 python python pip

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
safe YAML parsing, custom dumping, and safe_load with PyYAML
Pacotes
Símbolos
  • yaml.dump
  • yaml.safe_load
Ambiente
python
Criado
2026-08-27T18:02:51Z

Contrato

  1. yaml.safe_load parses YAML strings and streams into native Python dictionaries, lists, booleans, and scalar types.
  2. yaml.dump serializes Python data structures to formatted YAML strings with support for sort_keys and default_flow_style.
  3. yaml.safe_load accepts file-like stream objects (such as io.StringIO) and parses them identically to string input.
  4. yaml.safe_load raises yaml.YAMLError when encountering syntactically invalid or malformed YAML input.
  5. yaml.safe_load safely rejects dangerous arbitrary Python object instantiation tags (raising yaml.constructor.ConstructorError).
  6. yaml.SafeLoader and yaml.SafeDumper subclasses support custom constructors and representers for domain-specific tag serialization.

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

NOTES.md
# PyYAML safe_load and dump APIs

This sample pins `pyyaml` 6.0.3 and verifies safe YAML serialization and deserialization using `yaml.safe_load` and `yaml.dump`.

The contract verifies:
- `yaml.safe_load` parses YAML strings and streams containing mappings, sequences, numbers, booleans, nulls, and multiline blocks into native Python data structures.
- `yaml.dump` serializes Python objects to valid YAML with configurable options such as `sort_keys=True` and `default_flow_style=False`, preserving data roundtrip fidelity.
- `yaml.safe_load` raises `yaml.YAMLError` (e.g. `ScannerError`, `ParserError`) when parsing syntactically malformed YAML.
- `yaml.safe_load` securely rejects dangerous Python object instantiation tags (such as `!!python/object/apply`) and raises `yaml.constructor.ConstructorError`.
- Custom domain types can be safely serialized and deserialized using custom Loader/Dumper subclasses inheriting from `SafeLoader`/`SafeDumper` with registered constructors and representers.
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: safe YAML parsing, custom dumping, and safe_load with PyYAML
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/pyyaml@6.0.3
Demonstrate these symbols/APIs:
  - yaml.dump
  - yaml.safe_load

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:3a280cc7f7e9d5382cf511ec16b6012d1ddce87d98b57ad48747e5a325ad886a","contract":["yaml.safe_load parses YAML strings and streams into native Python dictionaries, lists, booleans, and scalar types.","yaml.dump serializes Python data structures to formatted YAML strings with support for sort_keys and default_flow_style.","yaml.safe_load accepts file-like stream objects (such as io.StringIO) and parses them identically to string input.","yaml.safe_load raises yaml.YAMLError when encountering syntactically invalid or malformed YAML input.","yaml.safe_load safely rejects dangerous arbitrary Python object instantiation tags (raising yaml.constructor.ConstructorError).","yaml.SafeLoader and yaml.SafeDumper subclasses support custom constructors and representers for domain-specific tag serialization."],"goal":"safe YAML parsing, custom dumping, and safe_load with PyYAML","kind":"HOW","packages":["pkg:pypi/pyyaml@6.0.3"],"schemaVersion":1,"symbols":["yaml.dump","yaml.safe_load"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","executionContext":"python","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/pyyaml@6.0.3"],"schemaVersion":1,"subject":"pkg:pypi/pyyaml@6.0.3","symbols":["yaml.dump","yaml.safe_load"],"verifierAdapter":"python@1"}
requirements.txt
pyyaml==6.0.3
spec.json
{
  "schemaVersion": 1,
  "goal": "safe YAML parsing, custom dumping, and safe_load with PyYAML",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/pyyaml@6.0.3"
  ],
  "symbols": [
    "yaml.dump",
    "yaml.safe_load"
  ]
}
test/contract.py
import io
import yaml
from yaml.constructor import ConstructorError
from yaml.error import YAMLError

# 1. Verify yaml.safe_load parses YAML strings into native Python dictionaries, lists, and primitives
yaml_text = """
server:
  host: 127.0.0.1
  port: 8080
  enabled: true
  null_field: null
  tags:
    - alpha
    - beta
  description: |
    Line 1
    Line 2
"""
data = yaml.safe_load(yaml_text)
assert isinstance(data, dict), f"Expected dict, got {type(data)}"
assert data["server"]["host"] == "127.0.0.1"
assert data["server"]["port"] == 8080
assert data["server"]["enabled"] is True
assert data["server"]["null_field"] is None
assert data["server"]["tags"] == ["alpha", "beta"]
assert data["server"]["description"].strip() == "Line 1\nLine 2"

# 2. Verify yaml.dump serializes data to YAML string and safe_load preserves roundtrip fidelity
payload = {
    "title": "Config",
    "count": 42,
    "items": ["apple", "banana"],
    "active": False,
}
dumped = yaml.dump(payload, sort_keys=True, default_flow_style=False)
assert "count: 42" in dumped
assert "title: Config" in dumped
reloaded = yaml.safe_load(dumped)
assert reloaded == payload

# 3. Verify yaml.safe_load accepts file-like stream objects (io.StringIO)
stream = io.StringIO("key: stream_value\ncount: 99\n")
stream_data = yaml.safe_load(stream)
assert stream_data == {"key": "stream_value", "count": 99}

# 4. Verify yaml.safe_load raises YAMLError on syntactically malformed YAML
try:
    yaml.safe_load("server: [unclosed list")
    raise AssertionError("Expected YAMLError on malformed yaml syntax")
except YAMLError:
    pass

# 5. Verify yaml.safe_load rejects dangerous python object instantiation tags
try:
    yaml.safe_load("!!python/object/apply:os.system ['echo unsafe']")
    raise AssertionError("Expected ConstructorError on unsafe python object tag")
except ConstructorError:
    pass

# 6. Verify custom domain objects can be serialized and parsed safely using SafeLoader/SafeDumper extensions
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        return isinstance(other, Point) and self.x == other.x and self.y == other.y

class CustomLoader(yaml.SafeLoader):
    pass

class CustomDumper(yaml.SafeDumper):
    pass

def point_constructor(loader, node):
    values = loader.construct_mapping(node)
    return Point(values["x"], values["y"])

def point_representer(dumper, data):
    return dumper.represent_mapping("!point", {"x": data.x, "y": data.y})

CustomLoader.add_constructor("!point", point_constructor)
CustomDumper.add_representer(Point, point_representer)

pt = Point(10, 20)
custom_yaml = yaml.dump({"location": pt}, Dumper=CustomDumper)
assert "!point" in custom_yaml
parsed_custom = yaml.load(custom_yaml, Loader=CustomLoader)
assert isinstance(parsed_custom["location"], Point)
assert parsed_custom["location"] == Point(10, 20)

print("CONTRACT PASS: pyyaml safe_load and dump verified offline")

Seeder de origem

anônimo