모듈 참조
pyrs_yaml 모듈의 전체 API 참조입니다.
버전 호환성
pyrs-yaml은 ABI3 휠로 빌드되어 Python 3.8부터 3.15까지 단일 휠로 지원합니다.
코어 함수¶
parse()¶
YAML 문자열 또는 바이트를 파싱하여 YamlDocument로 변환합니다.
parse(yaml: str | bytes, resolve_merges: bool = True, schema: str | dict = "core", max_depth: int = 1000, allow_duplicate_keys: bool | None = None, honor_version_directive: bool = False, duplicate_keys: str | None = None) -> YamlDocument
매개변수:
yaml—str또는bytesYAML 콘텐츠resolve_merges— 파싱 후 병합 키 (<<: *alias)를 해석할지 여부 (기본값:True)schema— 스키마 이름 ("core","json","failsafe","yaml1.1"또는 등록된 사용자 정의 이름), 또는 인라인 스키마 dict (YAML 스키마 언어 참조)max_depth— 최대 중첩 깊이 (기본값:1000)allow_duplicate_keys— 중복 매핑 키를 허용할지 여부 (기본값:None,"as_is"와 동일)duplicate_keys— 하나의 매핑에 YAML 이 같은 키로 세는 키가 둘 있을 때 읽는 쪽이 어떻게 행동하는지 (기본값:"as_is")."as_is"는 신원 등급마다 그동안과 같은 답을 준다: 스칼라 충돌과 일반/인용 표기의 충돌은 거부되고, 두 번째 null 키와 병합 키는 첫 자리에 접히며, 태그는 모든 값에서 두 키를 갈라 놓는다."error"는 기본이 면제하는 등급도 거부한다."last_wins"는 나중 쌍에 조용히 접는데, 이것이allow_duplicate_keys=True의 뜻이다."first_wins"는 앞선 쌍의 값을 지키고, 접히는 쪽의 주석과 앵커 정의는 남는 열쇠로 옮긴다. 이 항목과allow_duplicate_keys를 함께 넘기면 우선순위로 정하지 않고 거부한다.honor_version_directive— 명시된%YAML지시문에 대한 버전 협상 (기본값:False).True이면%YAML 1.1을 선언한 문서를 YAML 1.1 프로파일로 해석하고 지시문도 다시 씁니다. 명시한schema가 여전히 우선합니다.
반환값: 파싱된 YAML를 포함하는 YamlDocument
발생:
YamlParseError— 잘못된 YAML 구문YamlTypeError— 지정된 스키마를 찾을 수 없음TypeError— 입력이str또는bytes가 아님
예시:
doc = pyrs_yaml.parse("key: value")
doc = pyrs_yaml.parse(b"key: value")
doc = pyrs_yaml.parse(yaml_str, schema="json")
doc = pyrs_yaml.parse(
"addr: 0xFF", schema={"extends": "core", "rules": [{"pattern": "^0x[0-9a-fA-F]+$", "type": "int"}]}
)
parse_file()¶
YAML 파일을 파싱합니다.
parse_file(path: str, schema: str | dict = "core", max_depth: int = 1000, allow_duplicate_keys: bool | None = None, honor_version_directive: bool = False, duplicate_keys: str | None = None) -> YamlDocument
매개변수:
path— YAML 파일 경로
반환값: YamlDocument
발생:
IOError— 파일을 찾을 수 없거나 읽을 수 없음YamlParseError— 잘못된 YAML
예시:
doc = pyrs_yaml.parse_file("config.yaml")
parse_all_docs()¶
문자열에서 여러 YAML 문서를 파싱합니다.
parse_all_docs(yaml: str, resolve_merges: bool = True, schema: str | dict = "core", max_depth: int = 1000, allow_duplicate_keys: bool | None = None, honor_version_directive: bool = False, duplicate_keys: str | None = None) -> list[YamlDocument]
매개변수:
yaml—str또는bytesYAML 콘텐츠resolve_merges— 파싱 후 병합 키 (<<: *alias)를 해석할지 여부 (기본값:True)schema— 스키마 이름 ("core","json","failsafe","yaml1.1"또는 등록된 사용자 정의 이름), 또는 인라인 스키마 dict (YAML 스키마 언어 참조)max_depth— 최대 중첩 깊이 (기본값:1000)allow_duplicate_keys— 중복 매핑 키를 허용할지 여부 (기본값:None,"as_is"와 동일)duplicate_keys— 하나의 매핑에 YAML 이 같은 키로 세는 키가 둘 있을 때 읽는 쪽이 어떻게 행동하는지 (기본값:"as_is")."as_is"는 신원 등급마다 그동안과 같은 답을 준다: 스칼라 충돌과 일반/인용 표기의 충돌은 거부되고, 두 번째 null 키와 병합 키는 첫 자리에 접히며, 태그는 모든 값에서 두 키를 갈라 놓는다."error"는 기본이 면제하는 등급도 거부한다."last_wins"는 나중 쌍에 조용히 접는데, 이것이allow_duplicate_keys=True의 뜻이다."first_wins"는 앞선 쌍의 값을 지키고, 접히는 쪽의 주석과 앵커 정의는 남는 열쇠로 옮긴다. 이 항목과allow_duplicate_keys를 함께 넘기면 우선순위로 정하지 않고 거부한다.honor_version_directive— 명시된%YAML지시문에 대한 버전 협상 (기본값:False).True이면%YAML 1.1을 선언한 문서를 YAML 1.1 프로파일로 해석하고 지시문도 다시 씁니다. 명시한schema가 여전히 우선합니다.
반환값: YamlDocument 객체 목록
예시:
docs = pyrs_yaml.parse_all_docs("a: 1\n---\nb: 2")
PyYAML 호환 함수¶
safe_load()¶
YAML를 파싱하여 네이티브 Python 타입을 반환합니다.
safe_load(yaml: str, schema: str | dict = "core", max_depth: int = 1000, allow_duplicate_keys: bool | None = None, honor_version_directive: bool = False, duplicate_keys: str | None = None) -> dict[Any, Any] | list[Any]
매개변수:
yaml—str또는bytesYAML 콘텐츠schema— 스키마 이름 ("core","json","failsafe","yaml1.1"또는 등록된 사용자 정의 이름), 또는 인라인 스키마 dict (YAML 스키마 언어 참조)max_depth— 최대 중첩 깊이 (기본값:1000)allow_duplicate_keys— 중복 매핑 키를 허용할지 여부 (기본값:None,"as_is"와 동일)duplicate_keys— 하나의 매핑에 YAML 이 같은 키로 세는 키가 둘 있을 때 읽는 쪽이 어떻게 행동하는지 (기본값:"as_is")."as_is"는 신원 등급마다 그동안과 같은 답을 준다: 스칼라 충돌과 일반/인용 표기의 충돌은 거부되고, 두 번째 null 키와 병합 키는 첫 자리에 접히며, 태그는 모든 값에서 두 키를 갈라 놓는다."error"는 기본이 면제하는 등급도 거부한다."last_wins"는 나중 쌍에 조용히 접는데, 이것이allow_duplicate_keys=True의 뜻이다."first_wins"는 앞선 쌍의 값을 지키고, 접히는 쪽의 주석과 앵커 정의는 남는 열쇠로 옮긴다. 이 항목과allow_duplicate_keys를 함께 넘기면 우선순위로 정하지 않고 거부한다.honor_version_directive— 명시된%YAML지시문에 대한 버전 협상 (기본값:False).True이면%YAML 1.1을 선언한 문서를 YAML 1.1 프로파일로 해석하고 지시문도 다시 씁니다. 명시한schema가 여전히 우선합니다.
다음과 동일: PyYAML의 yaml.safe_load()
예시:
data = pyrs_yaml.safe_load("key: value") # {'key': 'value'}
safe_loads()¶
여러 YAML 문서를 파싱합니다.
safe_loads(yaml: str, schema: str | dict = "core", max_depth: int = 1000, allow_duplicate_keys: bool | None = None, honor_version_directive: bool = False, duplicate_keys: str | None = None) -> list[dict[Any, Any] | list[Any]]
매개변수:
yaml—str또는bytesYAML 콘텐츠schema— 스키마 이름 ("core","json","failsafe","yaml1.1"또는 등록된 사용자 정의 이름), 또는 인라인 스키마 dict (YAML 스키마 언어 참조)max_depth— 최대 중첩 깊이 (기본값:1000)allow_duplicate_keys— 중복 매핑 키를 허용할지 여부 (기본값:None,"as_is"와 동일)duplicate_keys— 하나의 매핑에 YAML 이 같은 키로 세는 키가 둘 있을 때 읽는 쪽이 어떻게 행동하는지 (기본값:"as_is")."as_is"는 신원 등급마다 그동안과 같은 답을 준다: 스칼라 충돌과 일반/인용 표기의 충돌은 거부되고, 두 번째 null 키와 병합 키는 첫 자리에 접히며, 태그는 모든 값에서 두 키를 갈라 놓는다."error"는 기본이 면제하는 등급도 거부한다."last_wins"는 나중 쌍에 조용히 접는데, 이것이allow_duplicate_keys=True의 뜻이다."first_wins"는 앞선 쌍의 값을 지키고, 접히는 쪽의 주석과 앵커 정의는 남는 열쇠로 옮긴다. 이 항목과allow_duplicate_keys를 함께 넘기면 우선순위로 정하지 않고 거부한다.honor_version_directive— 명시된%YAML지시문에 대한 버전 협상 (기본값:False).True이면%YAML 1.1을 선언한 문서를 YAML 1.1 프로파일로 해석하고 지시문도 다시 씁니다. 명시한schema가 여전히 우선합니다.
다음과 동일: PyYAML의 yaml.safe_loads()
safe_dump()¶
Python 객체를 YAML로 직렬화합니다.
safe_dump(data: dict[str, Any] | list[Any] | ndarray) -> str
다음과 동일: PyYAML의 yaml.safe_dump()
지원되는 입력 타입: dict, list, str, int, float, bool, None, 그리고 numpy.ndarray (모든 차원과 숫자 dtype: int8/16/32/64, uint8/16/32/64, float32/64, complex64/128, bool)
safe_dumps()¶
safe_dump()의 별칭입니다.
safe_dumps(data: dict[str, Any] | list[Any] | ndarray) -> str
:material-json: 변환 함수¶
from_dict()¶
Python dict를 YAML 문자열로 변환합니다. dict 값으로 numpy.ndarray도 허용됩니다.
from_dict(data: dict[str, Any]) -> str
from_json()¶
JSON 문자열을 YAML 문자열로 변환합니다.
from_json(json_str: str) -> str
dump_file()¶
Python 객체를 YAML로 직렬화하여 파일에 씁니다. dict, list 또는 numpy.ndarray를 허용합니다.
dump_file(data: Any, path: str) -> None
Pydantic 통합¶
dump_pydantic()¶
Pydantic 모델을 YAML 문자열로 직렬화합니다.
dump_pydantic(model: BaseModel) -> str
model_dump(mode='json')를 사용하여 문자열 타입을 유지한 다음(예: "10001" 우편번호는 문자열로 유지), safe_dump에 위임합니다.
발생:
ImportError— pydantic이 설치되지 않음TypeError—model이 PydanticBaseModel인스턴스가 아님
예시:
from pydantic import BaseModel
import pyrs_yaml
class User(BaseModel):
name: str
age: int
yaml_str = pyrs_yaml.dump_pydantic(User(name="Alice", age=30))
parse_as()¶
YAML 문자열을 파싱하고 Pydantic 모델에 대해 검증합니다.
parse_as(model: type[BaseModel], src: str, **yaml_kwargs: Any) -> BaseModel
매개변수:
model— PydanticBaseModel하위 클래스src— 파싱할 YAML 문자열**yaml_kwargs—YAML()생성자로 전달되는 키워드 인자
발생:
ImportError— pydantic이 설치되지 않음TypeError—model이 PydanticBaseModel하위 클래스가 아님pydantic.ValidationError— 파싱된 데이터가 모델 검증에 실패
예시:
user = pyrs_yaml.parse_as(User, "name: Alice\nage: 30")
print(user.name) # Alice
PyrsYamlConfigSettingsSource¶
pydantic-settings YAML 소스를 pyrs-yaml로 구현한 클래스. pydantic_settings.YamlConfigSettingsSource의 드롭인 대체품으로, PyYAML 대신 pyrs-yaml을 파서로 사용합니다.
PyrsYamlConfigSettingsSource(
settings_cls: type[BaseSettings],
yaml_file: ConfigFileSourceType | None = DEFAULT_PATH,
yaml_file_encoding: str | None = None,
yaml_config_section: str | None = None,
deep_merge: bool = False,
)
SettingsConfigDict(yaml_file=...)(또는 직접 전달)로 선언된 YAML 파일에서 설정을 로드한 뒤 pyrs-yaml 파서(YAML 1.2 코어 스키마)로 해석합니다. 환경 변수·dotenv 덮어쓰기, yaml_config_section(점 표기 경로 지원), 여러 파일의 deep_merge, yaml_file_encoding 등 다른 pydantic-settings 기능은 YamlConfigSettingsSource와 동일하게 동작합니다.
예외:
ImportError— pydantic-settings가 설치되지 않은 경우(pyrs-yaml[settings]설치)
예제:
from pydantic_settings import BaseSettings, SettingsConfigDict
import pyrs_yaml
class Settings(BaseSettings):
app_name: str
model_config = SettingsConfigDict(yaml_file="config.yaml")
@classmethod
def settings_customise_sources(
cls, settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings
):
return (
init_settings,
env_settings,
dotenv_settings,
file_secret_settings,
pyrs_yaml.PyrsYamlConfigSettingsSource(settings_cls),
)
참고: 이 클래스는 지연 내보내기됩니다 —
import pyrs_yaml에 pydantic-settings가 필요 없습니다. pydantic-settings가 설치되지 않은 상태에서pyrs_yaml.PyrsYamlConfigSettingsSource에 접근하면 설치 방법을 안내하는ImportError가 발생합니다.
태그 레지스트리¶
register_tag()¶
사용자 정의 태그 핸들러를 등록합니다. 데코레이터와 명령형 두 형식을 모두 지원합니다.
register_tag(name: str, handler: Callable | None = None, priority: int = 0) -> Callable
예시:
@pyrs_yaml.register_tag("!custom")
def handler(node):
return f"custom:{node}"
pyrs_yaml.register_tag("!custom", handler_fn, priority=1)
remove_tag()¶
태그 핸들러를 제거합니다.
remove_tag(name: str) -> None
clear_tag_handlers()¶
등록된 모든 태그 핸들러를 제거합니다.
clear_tag_handlers() -> None
YAML 스키마 언어¶
사용자 정의 스키마를 정의하여 일반 스칼라가 Python 타입으로 해석되는 방식을 제어합니다.
register_schema()¶
사용자 정의 스키마를 등록합니다.
register_schema(name: str, schema_yaml: str) -> None
매개변수:
name— 스키마 이름schema_yaml— YAML 문자열(extends,rules,validate키 포함). 인라인 dict는YAML(schema=...)이 받습니다
예제:
import pyrs_yaml
# YAML 문자열에서 사용자 정의 스키마 등록
pyrs_yaml.register_schema(
"hex",
"""
name: hex
extends: core
rules:
- pattern: ^0x[0-9a-fA-F]+$
type: int
""",
)
# 사용자 정의 스키마 사용
y = pyrs_yaml.YAML(schema="hex")
doc = y.parse("addr: 0xFF")
assert doc.get("addr") == 255
d = pyrs_yaml.safe_load("addr: 0x1F", schema="hex")
assert d["addr"] == 31
인라인 스키마 dict¶
등록하지 않고 dict를 직접 전달:
d = pyrs_yaml.safe_load(
"addr: 0xFF",
schema={
"extends": "core",
"rules": [{"pattern": "^0x[0-9a-fA-F]+$", "type": "int"}],
},
)
extends— 선택적 기본 스키마(core,json,failsafe,yaml1.1)rules— 순서가 있는{pattern, type}목록; 첫 번째 일치 항목이 적용- 지원 타입 :
null,bool,int,float,str - 내장 Core 스키마는 계속 제로 비용
match디스패치 사용(영향 없음) - 파일 I/O —
load_schema(name, path)로 YAML 파일에서 스키마 로드;list_schemas()로 등록된 모든 스키마 반환
커뮤니티 플러그인¶
사용자 정의 YAML 노드 타입을 정의하여 직렬화 및 역직렬화에 통합합니다.
CustomType¶
사용자 정의 타입의 기본 클래스.
class CustomType:
python_type: type
def from_yaml(self, value: str) -> Any: ...
def to_yaml(self, obj: Any) -> str: ...
def can_parse(self, node: CustomNode) -> bool: ...
def validate(self, obj: Any) -> bool: ...
register_type()¶
사용자 정의 타입을 등록합니다.
register_type(name: str, handler: CustomType | None = None) -> None
예제:
from datetime import datetime
class TimestampType(pyrs_yaml.CustomType):
python_type = datetime
def from_yaml(self, value: str):
return datetime.fromisoformat(value)
def to_yaml(self, obj) -> str:
return obj.isoformat()
pyrs_yaml.register_type("!timestamp", TimestampType())
# 로드: 태그된 스칼라 → Python 객체
doc = pyrs_yaml.parse("when: !timestamp 2026-08-11T10:30:00")
assert isinstance(doc.get("when"), datetime)
# 덤프: Python 객체 → 태그된 스칼라
data = {"ts": datetime(2026, 8, 11, 10, 30)}
out = pyrs_yaml.safe_dump(data)
# out에 포함됨: !!timestamp 2026-08-11T10:30:00
| 메서드 | 설명 |
|---|---|
can_parse(node) |
이 타입이 주어진 AST 노드를 처리하는지 여부 |
from_yaml(value) |
YAML 문자열을 Python 객체로 변환 |
to_yaml(obj) |
Python 객체를 YAML 문자열로 변환 |
validate(obj) |
Python 객체 검증(bool 반환) |
remove_type()¶
등록된 타입을 제거합니다.
remove_type(name: str) -> None
clear_type_handlers()¶
등록된 모든 타입 핸들러를 제거합니다.
clear_type_handlers() -> None
컴플라이언스¶
compliance_report()¶
YAML 테스트 스위트 컴플라이언스 보고서를 계산합니다.
compliance_report() -> dict
YAML 테스트 스위트 통과율과 테스트별 결과를 반환합니다.
스트리밍 이벤트¶
parse_stream()¶
문서를 점진적으로 파싱하여 원시 이벤트 dict를 생성합니다.
parse_stream(
yaml: str | bytes, on_event=None, max_depth=1000, *, format="yaml"
) -> StreamIterator | None
각 단계마다 이벤트 dict를 생성하는 StreamIterator를 반환합니다. YAML().load_stream()(Python 값으로 해석)과 달리 원시 토큰 스트림을 노출합니다.
format은 누가 이벤트를 만드는지 고릅니다 — yaml(기본), json, jsonc, json5, toml. 모든 생성자가 같은 어휘를 보고하므로 dict는 언제나 같은 아홉 키(type, value, style, anchor, tag, line, column, offset, end)를 가집니다. offset과 end는 이벤트 자체 토큰의 소스 바이트 범위이고 — source.encode()[event["offset"]:event["end"]]가 그것을 디코딩합니다 — 프로듀서가 위치만 기록하는 자리, 즉 TOML의 모든 이벤트에서는 end가 offset과 같습니다. comment 이벤트에는 열 번째 키 owner가 더 실려, 그 주석이 어느 노드의 어느 칸에 정리되는지 이름 붙입니다. 그 형식이 할 말이 없는 필드는 None으로 남습니다. anchor도 alias도 YAML 고유라 다른 형식에서는 나타나지 않고, TOML의 리터럴 '…'은 기본 문자열 "…"과 똑같이 읽힙니다 — 어떤 인용표를 쳤는지가 중간 표현식에 남지 않기 때문입니다. JSON이나 TOML 스트림은 문서 하나만 싣고, 승인 여부를 판정하는 스캐너는 트리를 가는 경로가 쓰는 그 스캐너와 같습니다. 키별 표는 스트리밍 파싱을 참고하세요.
YamlStream¶
YamlStream 클래스는 YAML().load_stream() 및 YAML().load_stream_file()이 반환하는 지연 이벤트 반복자입니다. 전체 문서를 메모리에 로드하지 않고 파싱된 이벤트 dict를 한 번에 하나씩 생성합니다.
stream = yaml.load_stream_file("large.yaml")
for event in stream:
print(event)
전체 API 세부 정보는 YamlStream을 참조하세요.
비동기 함수¶
asyncio.run_in_executor를 사용한 비동기 I/O 래퍼. 이벤트 루프 컨텍스트에서 논블로킹.
safe_dumps_async()¶
Python 객체를 YAML 문자열로 직렬화 (비동기).
async def safe_dumps_async(data: Any) -> str
safe_dump_async()¶
Python 객체를 YAML 형식으로 stdout에 출력 (비동기).
async def safe_dump_async(data: Any) -> None
safe_loads_async()¶
YAML 문자열을 네이티브 Python 객체로 파싱 (비동기).
async def safe_loads_async(yaml: str, schema: str = "core") -> Any
safe_load_async()¶
YAML 문자열을 네이티브 Python 객체로 파싱 (비동기).
async def safe_load_async(yaml: str, schema: str = "core") -> Any
예시:
import asyncio, pyrs_yaml
async def main():
yaml = await pyrs_yaml.safe_dumps_async({"a": 1})
data = await pyrs_yaml.safe_loads_async(yaml)
print(data) # {'a': 1}
asyncio.run(main())
Markdown Front Matter¶
read_markdown()¶
Markdown 파일에서 YAML Front Matter를 추출합니다.
read_markdown(path: str, schema: str = "core", max_depth: int = 1000) -> tuple[dict[Any, Any] | None, str]
반환값: (frontmatter_dict, content_string). Front Matter가 없으면 frontmatter는 None.
read_markdown_str()¶
Markdown 문자열에서 YAML Front Matter를 추출합니다.
read_markdown_str(content: str, schema: str = "core", max_depth: int = 1000) -> tuple[dict[Any, Any] | None, str]
i18n 함수¶
set_language()¶
오류 메시지의 언어를 설정합니다.
set_language(lang: str) -> None
지원: "en", "zh-CN", "ja-JP", "ko-KR"
get_language()¶
현재 언어를 가져옵니다.
get_language() -> str
list_languages()¶
지원되는 모든 언어를 나열합니다.
list_languages() -> list[str]
detect_language()¶
환경 변수에서 사용자의 선호 언어를 자동 감지합니다.
detect_language() -> str
negotiate_language()¶
BCP 47 언어 협상.
negotiate_language(user_locales: list[str], default: str = "en") -> str
예외¶
YamlParseError— YAML 파싱 오류 (ValueError상속)YamlSerializeError— YAML 직렬화 오류 (ValueError상속)YamlTypeError— 타입 변환 오류 (TypeError상속)YamlValidateError— JSON Schema 검증 오류 (ValueError상속)YamlEditError— 제자리 편집 오류 (ValueError상속)YamlPathError— YAML 경로 오류 (ValueError상속)YamlDocumentError— 오래된Node접근 오류 (Exception상속)YamlDuplicateKeyError— 중복 매핑 키 오류 (ValueError상속)YamlMaxDepthError— 최대 중첩 깊이 초과 (ValueError상속)YamlTagError— 태그 핸들러 오류 (ValueError상속)YamlTagSkip— 노드를 다음 핸들러로 넘기는 제어 흐름 센티널 (YamlTagError상속)
Document.validate()는 이 계열 안에서 답합니다. 규칙 평가는 jsonschema에 위임되는데 여기의
무엇도 그 패키지를 설치하지 않습니다 — 패키지는 typing-extensions에만 의존하고 extras는
cli, pydantic, settings입니다 — 따라서 검증 전에 pip install jsonschema를 실행하세요.
import 가능한 평가 엔진이 없으면 호출은 그 설치 경로를 밝히고 import 오류를 실은
YamlValidateError를 발생시킵니다. 스키마가 통과시켰을 문서에서도 마찬가지입니다. 텍스트로
주어진 schema는 이 패키지 자신의 길로, 평가 전에 json.loads로 읽히고 JSON이 아닌 텍스트는
YamlValidateError(schema text must be JSON (…); pass the schema as a dict if it is not JSON)로
거부되므로 YAML 철자도 계열 안에 머뭅니다. 평가 엔진이 배포물에 없는 것은 알려진 경계이며
사용자 문서로는 빠른 시작과
사용자 정의 스키마에 적었습니다.
자세한 내용은 예외 페이지를 참조하세요.
버전¶
__version__ = "0.19.1"
자동 생성 API 참조¶
아래 내용은 mkdocstrings가 라이브러리 자체 docstring과 생성된 형식 stub에서 그려 낸 것이므로, 서명은 코드에서 온 것이지 손으로 옮긴 것이 아닙니다.
pyrs_yaml
¶
pyrs-yaml: High-performance Python library for YAML, TOML, JSON, JSONC and JSON5 with perfect round-trip support, built with Rust and PyO3.
This module provides Rust-backed parsers and serializers for all five formats, preserving comments, anchors, tags, and source formatting across round-trip conversions.
Example
import pyrs_yaml doc = pyrs_yaml.parse("key: value") print(doc.to_yaml()) key: value print(doc.get("key")) value
CustomType
¶
Base class for custom YAML node types.
Subclass this to define a custom type that can be used with YAML tags:
class TimestampType(CustomType):
python_type = datetime # optional: for serialization isinstance check
def from_yaml(self, value):
return datetime.fromisoformat(value)
def to_yaml(self, obj):
return obj.isoformat()
def can_parse(self, node):
return True
register_type("!timestamp", TimestampType())
can_parse
¶
can_parse(value)
Return True if this type should handle the given value.
value is the schema-resolved Python value (str, int, dict, list,
etc.). Defaults to True: the tag match alone is sufficient. Override
to gate handling on value content (e.g. value prefix).
Source code in python/pyrs_yaml/_type_registry.py
35 36 37 38 39 40 41 42 | |
from_yaml
¶
from_yaml(value)
Convert a schema-resolved Python value to the target Python object.
value is the already-resolved Python value (str, int, dict, list,
None, etc.). For scalar tags this is a str; for structured tags
(e.g. !set) it can be a dict or list.
Source code in python/pyrs_yaml/_type_registry.py
44 45 46 47 48 49 50 51 | |
to_yaml
¶
to_yaml(obj)
Convert a Python object to a YAML string value.
Source code in python/pyrs_yaml/_type_registry.py
53 54 55 | |
validate
¶
validate(obj)
Validate a Python object's type and value.
Source code in python/pyrs_yaml/_type_registry.py
57 58 59 | |
JsonLines
¶
Iterator over the values of a line-delimited JSON stream, one document per line.
__next__
¶
__next__()
Yield the next line's value; None once the stream is exhausted.
A line the stream refuses raises with its position in the whole input, and the cursor does not move: asking again reports the same record rather than the one after it, because a record this format defines is not one to lose silently.
YamlStream
¶
Lazy, constant-memory stream of YAML documents from a [ChunkCharIter].
__next__ parses exactly one event per call (driving the granit parser
incrementally), so a large file is never fully buffered. Errors surface
exactly once as a YamlParseError; after an error or close() the
iterator returns None (StopIteration).
parse
¶
parse(
yaml,
resolve_merges=True,
schema=None,
max_depth=1000,
allow_duplicate_keys=None,
honor_version_directive=False,
duplicate_keys=None,
)
Source code in python/pyrs_yaml/__init__.py
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | |
parse_file
¶
parse_file(
path,
schema=None,
max_depth=1000,
allow_duplicate_keys=None,
honor_version_directive=False,
duplicate_keys=None,
)
Source code in python/pyrs_yaml/__init__.py
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 | |
parse_all_docs
¶
parse_all_docs(
yaml,
resolve_merges=True,
schema=None,
max_depth=1000,
allow_duplicate_keys=None,
honor_version_directive=False,
duplicate_keys=None,
)
Source code in python/pyrs_yaml/__init__.py
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 | |
parse_stream
builtin
¶
parse_stream(
yaml, on_event=None, max_depth=1000, *, format="yaml"
)
Event-stream parsing. With on_event callback, consumes events and returns None. Otherwise returns a lazy StreamIterator.
format chooses the producer: yaml (the default), json, jsonc, json5 or toml. Every
producer reports the one vocabulary, so the dicts keep the same keys and only the fields a
format has something to say about change. style is whatever that engine remembers: a JSON
string reads double_quoted and a JSON number plain, JSON5 adds single_quoted, and a TOML
literal '…' reads the same as a basic "…" because which quote was typed is not in its IR.
anchor and alias stay YAML's own and never appear elsewhere. A comment event carries two
keys about the note: style says whether the source gave the note a line of its own, and
owner says which node the note is filed under and in which of its two slots — the node the
consumer builds next (following_leading, following_inline) or the one it built last
(preceding_leading, preceding_inline). max_depth bounds the YAML and
JSON readers, which carry that knob; TOML's nesting limit is the intermediate representation's
own. The accept/reject verdict is the same one the tree route reaches with the same detail,
because it is the same scanner: a document load_json refuses raises here too.
With on_event the events arrive as they are produced and returning False stops the producer,
not merely the delivery loop. What can stop is the format's own fact: json/jsonc/json5
stop scanning before the bytes of the next event, so a syntax error past that point is never
reached; toml stops emitting from the intermediate representation its scan already built, so a
refused document still raises — before any event is delivered. YAML's text producer is a push
adapter over a scanner that cannot be aborted, so there False stops delivery after the whole
document was parsed; load_stream is YAML's incremental surface. Without on_event the
iterator materialises the document first.
safe_load
¶
safe_load(
yaml,
schema=None,
max_depth=1000,
allow_duplicate_keys=None,
honor_version_directive=False,
duplicate_keys=None,
)
Source code in python/pyrs_yaml/__init__.py
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 | |
safe_loads
¶
safe_loads(
yaml,
schema=None,
max_depth=1000,
allow_duplicate_keys=None,
honor_version_directive=False,
duplicate_keys=None,
)
Source code in python/pyrs_yaml/__init__.py
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 | |
safe_dump
builtin
¶
safe_dump(data)
Serialize a Python dict/list to a YAML string.
A tuple is read as a sequence, which is the shape the loader hands back for a YAML sequence
key: safe_dump(safe_load(text)) has to accept what safe_load produced.
from_dict
builtin
¶
from_dict(data)
Convert a Python dict/list to a YAML string (auto-selects block/flow style).
A tuple is read as a sequence; see [safe_dump].
from_jsonc
builtin
¶
from_jsonc(json_str)
Convert a JSONC string (JSON with // and /* ... */ comments) to
a YAML string. Comments are NOT discarded on this projection: since
112/#115 they ride the AST's comment / leading_comment slots (so¶
to_jsonc can reproduce them), and the YAML writer renders those slots
as # notes, which keeps the conversion lossless. Strictly a
//-to-# change of syntax, not a change of language: everything else
matches from_json semantics exactly.
from_json5
builtin
¶
from_json5(json_str)
Convert a JSON5 string to a YAML string. JSON5 supersedes JSONC with
trailing commas, single-quoted strings, unquoted identifier keys and
the 0x… / .5 / Infinity / NaN numeric forms; like from_jsonc,
comments survive the projection as YAML notes rather than being dropped.
from_toml
builtin
¶
from_toml(toml_str)
Convert a TOML string to a YAML string (hub-and-spoke exchange).
TOML strings keep quoting so values never re-resolve; datetimes gain
the !timestamp tag consumed by the built-in plugin.
load_json
builtin
¶
load_json(json_str)
Parse a strict JSON document directly into Python values (dict / list /
scalar), mirroring the load_jsonc / load_json5 / load_toml family.
Unlike load_jsonc this REJECTS the JSONC/JSON5 extensions — // and
/* … */ comments, trailing commas, single-quoted strings, bare
Infinity/NaN and 0x… forms all raise a parse error, exactly like
json.loads / orjson.loads. Canonical strict JSON takes the same
AST-free fast path load_jsonc uses (bytes → PyList/PyDict/scalars);
any non-canonical shape (floats with exotic spellings, \u escapes,
out-of-range ints) falls back to the strict AST parser that produces the
identical value or the proper json-parse-error.
load_jsonc
builtin
¶
load_jsonc(json_str)
Parse a JSONC document directly into Python values (dict / list /
scalar). Handy for TypeScript tsconfig.json, VS Code
settings.json, and similar dialects without a pre-processing step.
load_json5
builtin
¶
load_json5(json_str)
Parse a JSON5 document directly into Python values (dict / list /
scalar). Accepts the full JSON5 grammar without a pre-processing
step, mirroring load_jsonc on the wider dialect. Canonical strict
JSON takes the same AST-free fast path load_json and load_jsonc
use; every JSON5-only form falls through to the AST parser that owns
the dialect's number and string semantics.
load_json_lines
builtin
¶
load_json_lines(json_str)
Iterate the values of a line-delimited JSON stream (NDJSON, JSON Lines, .jsonl): one
complete document per line, resolved as the iterator is asked for rather than all up front.
Each value is what load_json returns for that line, and the stream keeps the engine's
contract: a blank line, a line holding only a note, or a value that needs the next line to
finish raises with its position in the whole input, and the refusal is reported again until the
iteration stops.
load_toml
builtin
¶
load_toml(toml_str)
Parse TOML directly into a Python dict (values, not a document). Anchors cannot occur in TOML, so no alias resolution pass is needed.
load_ini
¶
load_ini(text)
Parse INI text into a {section: {key: value}} dict.
Values are returned as raw strings (typed interpretation is left to
the caller). Anonymous leading key = value lines land under the
DEFAULT section and are inlined into every section, matching
configparser semantics.
Source code in python/pyrs_yaml/ini.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | |
to_toml
builtin
¶
to_toml(yaml, schema='core')
Render a YAML document as TOML text. Rejects shapes TOML cannot hold
(non-table root, null values, aliases, non-scalar keys) with stable
toml-serialize-error messages.
read_markdown
¶
read_markdown(path, schema='core', max_depth=1000)
Read a Markdown file and extract its YAML front matter, returning (frontmatter, body).
The argument is a path, not the text: read_markdown_str is the variant that takes content. The parameter was
named content here while the native function it forwards to reads the file at that value, so the keyword
path= - the only one that describes what the argument is - raised TypeError, and introspection reported a
signature the runtime did not honour.
Source code in python/pyrs_yaml/__init__.py
356 357 358 359 360 361 362 363 364 365 366 367 368 | |
read_markdown_str
¶
read_markdown_str(content, schema='core', max_depth=1000)
Extract YAML front matter from a Markdown string, returning (frontmatter, body).
Source code in python/pyrs_yaml/__init__.py
371 372 373 374 375 376 377 | |
register_tag
¶
register_tag(
name: str, handler: _F, priority: int = 0
) -> _F
register_tag(
name: str, handler: None = None, priority: int = 0
) -> Callable[[_F], _F]
register_tag(name, handler=None, priority=0)
Register a tag handler.
Supports both decorator and imperative forms
@register_tag("!custom") def handler(node): ...
@register_tag("!custom", priority=1) def handler(node): ...
register_tag("!custom", handler_fn) register_tag("!custom", handler_fn, priority=1)
Source code in python/pyrs_yaml/__init__.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | |
register_type
¶
register_type(name: str, handler: _T) -> _T
register_type(
name: str, handler: None = None
) -> Callable[[type[_T] | _T], type[_T] | _T]
register_type(name, handler=None)
Register a CustomType handler.
Supports both imperative and decorator forms:
register_type("!timestamp", TimestampType())
@register_type("!timestamp")
class TimestampType(CustomType):
def from_yaml(self, value):
return datetime.fromisoformat(value)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
The tag name (e.g. "!timestamp"). |
required | |
handler
|
A CustomType instance, or None for decorator form. |
None
|
Source code in python/pyrs_yaml/_type_registry.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
register_schema
builtin
¶
register_schema(name, schema_yaml)
Register a YAML Schema Language schema under a name.
schema_yaml is a schema definition in YAML format:
name: myapp
extends: core
rules:
- pattern: "^0x[0-9a-fA-F]+$"
type: int
YAML(schema="myapp").
list_schemas
builtin
¶
list_schemas()
List all registered schema names (built-in + custom).
Returns the four built-in schemas (failsafe, json, core, yaml1.1)
plus any schemas registered via register_schema() / load_schema().
load_schema
builtin
¶
load_schema(name, path)
Register a YAML Schema Language schema from a file.
Reads the schema definition from path (a YAML file with name/extends/rules
structure) and registers it under name. Equivalent to calling
register_schema(name, open(path).read()) but handles file I/O in Rust.
compliance_report
¶
compliance_report(suite_dir=None)
Run the YAML Test Suite and return a compliance report.
The suite data is a dev artifact (Reference/yaml-test-suite), not
bundled in the wheel; pass suite_dir when it lives elsewhere.
Source code in python/pyrs_yaml/compliance.py
263 264 265 266 267 268 269 270 271 272 273 274 275 | |
validate_custom_types
builtin
¶
validate_custom_types(obj)
Validate a Python object against all registered CustomType validators.
Recursively walks dicts and lists. For each value that matches a
registered type's python_type, calls the handler's validate method.
Raises ValueError if any value fails validation.
negotiate_language
builtin
¶
negotiate_language(user_locales, default='en')
Negotiate a language from user locale list and default.
discover_plugins
¶
discover_plugins(force=False)
Re-discover third-party plugins via entry_points.
By default, only plugins not yet loaded are processed. Set force=True
to re-run discovery for all plugins (including those that previously
failed or were already loaded).
Source code in python/pyrs_yaml/plugins/__init__.py
58 59 60 61 62 63 64 65 66 | |
get_plugin
builtin
¶
get_plugin(tag)
Get metadata for a registered plugin by tag.
Returns (tag, python_type) or None if the tag is not registered.
list_plugins
builtin
¶
list_plugins()
List all registered custom type plugins with their metadata.
Returns a list of (tag, python_type) tuples for every registered
CustomType handler.
get_discovery_errors
¶
get_discovery_errors()
Return a list of error messages from the last plugin discovery run.
Source code in python/pyrs_yaml/plugins/__init__.py
69 70 71 | |