샘플
pyyaml 6.0.3: safe YAML parsing, custom dumping, and safe_load with PyYAML
검증된 샘플 — pypi pyyaml 6.0.3: safe YAML parsing, custom dumping, and safe_load with PyYAML. python 3.12 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.
sha256:f33b03c1fbf97dc469bbba37b68bc06aba094a2206d9f39056a821a0f1d6c247
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 1
- 빌드한 서명 키
- 1
선언된 환경
python linux 24 · ubuntu · glibc 2.39 x64 python python pip
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| 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 |
케이스
HOW- 목표
- safe YAML parsing, custom dumping, and safe_load with PyYAML
- 패키지
- 심벌
-
- yaml.dump
- yaml.safe_load
- 환경
- python
- 생성일
- 2026-08-27T18:02:51Z
컨트랙트
- 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.
파일
- NOTES.md
- PROMPT.md
- csx.json
- requirements.txt
- spec.json
- test/contract.py
소스
# 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.
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.
{"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"}
pyyaml==6.0.3
{
"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"
]
}
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")
오리진 시더
익명