モジュールリファレンス
バージョン互換性
pyrs-yaml は ABI3 アプローチにより、単一のホイールで Python 3.8 から 3.15 まで対応しています。再コンパイルは不要です。
pyrs_yaml モジュールの完全な API リファレンス。
コア関数¶
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またはbytesの YAML コンテンツ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またはbytesの YAML コンテンツ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またはbytesの YAML コンテンツ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またはbytesの YAML コンテンツ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が Pydantic のBaseModelインスタンスでない
例:
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— Pydantic のBaseModelサブクラスsrc— パースする YAML 文字列**yaml_kwargs—YAML()コンストラクタに転送されるキーワード引数
スロー:
ImportError— pydantic がインストールされていないTypeError—modelが Pydantic のBaseModelサブクラスでない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
各ステップで 1 つのイベント dict を生成する StreamIterator を返します。YAML().load_stream()(Python 値に解決される)とは異なり、生のトークンストリームを公開します。
format はどの生産者が読むかを決めます — yaml(既定)、json、jsonc、json5、toml。どの生産者も同じ語彙を報告するので、dict は常に同じ 9 つのキー(type、value、style、anchor、tag、line、column、offset、end)を持ちます。offset と end はそのイベント自身のトークンのソースバイト範囲です — source.encode()[event["offset"]:event["end"]] でデコードできます。位置だけを記録する生産者では(すべての TOML イベントがそうです)、end は offset と等しくなります。comment イベントは 10 番目のキー owner を持ち、注釈がどのノードのどのスロットにまとめられているかを名乗ります。そのフォーマットが何も言えないフィールドは None のままです。anchor も alias も YAML 固有で、他の形式では現れません。TOML のリテラル '…' は基本文字列 "…" と同じ読みになります — どちらの引用符を使ったかは中間表現に残らないためです。JSON と TOML のストリームは 1 つのドキュメントだけを運び、採用か拒否かの判定はツリーを歩く経路と同じ答えになります。同じスキャナーが応えるからです。キーごとの表は ストリーミングイベント を参照してください。
YamlStream¶
YamlStream クラスは、YAML().load_stream() と YAML().load_stream_file() が返す遅延イベントイテレータです。ドキュメント全体をメモリに読み込まずに、パース済みのイベント dict を一度に 1 つ生成します。
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 オブジェクトを stdout に YAML として出力 (非同期)。
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 のみに依存し、extra は
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 と生成された型スタブから描画するため、署名はコード由来であり書き写しではありません。
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 | |