クイックスタート
このガイドでは、pyrs-yaml を数分で使い始める方法を説明します。
1. インストール¶
PyPI からインストール:
pip install pyrs-yaml
2. YAML のパース¶
import pyrs_yaml
# Parse a YAML string
doc = pyrs_yaml.parse("""
name: Alice
age: 30
email: alice@example.com
""")
# Access values
print(doc.get("name")) # Alice
print(doc.get("age")) # 30
print(doc.get("email")) # alice@example.com
3. Python オブジェクトへの変換¶
# Use safe_load for PyYAML-compatible behavior
data = pyrs_yaml.safe_load("""
users:
- name: Alice
role: admin
- name: Bob
role: user
""")
# Returns native Python types (dict, list, str, int, etc.)
print(data["users"][0]["name"]) # Alice
print(type(data["users"])) # <class 'list'>
4. YAML へのシリアライズ¶
# Convert a Python dict back to YAML
yaml_str = pyrs_yaml.safe_dump({"database": {"host": "localhost", "port": 5432, "name": "mydb"}})
print(yaml_str)
# database:
# host: localhost
# port: 5432
# name: mydb
5. フォーマットの保持(ラウンドトリップ)¶
# The key advantage of pyrs-yaml
original = """
# Server configuration
server:
host: 0.0.0.0
port: 8080
# Database settings
database: &db
host: localhost
port: 5432
# Use the database anchor
api:
<<: *db
endpoint: /api/v1
"""
# Parse and re-serialize — comments and anchors preserved
doc = pyrs_yaml.parse(original) # (1)!
output = doc.to_yaml() # (2)!
# The output matches the input (or is semantically equivalent)
assert "# Server configuration" in output # (3)!
assert "&db" in output # (4)!
-
parseはすべてのコメント、アンカー、タグ、スタイルを保持するYamlDocumentを構築します。 -
to_yamlは AST から再シリアライズし、フォーマットを保持します — 文字列操作なし。 - 独立コメントはそのまま保持されます。
- アンカー(
&db)、エイリアス(*db)、マージキー(<<)がすべて保持されます。
6. インプレース編集¶
# コメントやフォーマットを失わずに解析済みドキュメントを編集
doc = pyrs_yaml.parse("""
server:
host: localhost # bind address
ports:
- 8080
""")
doc.set("$.server.host", "0.0.0.0") # パスで置換
doc.append("$.server.ports", 443) # シーケンスに追加
print(doc.to_yaml())
# server:
# host: 0.0.0.0 # bind address
# ports:
# - 8080
# - 443
完全な API は インプレース編集ガイド を参照してください。
7. ファイルから YAML を読み込む¶
# Parse a YAML file directly
doc = pyrs_yaml.parse_file("config.yaml")
print(doc.get("name"))
8. 複数ドキュメント¶
# Parse multiple YAML documents
yaml_text = """
---
name: config1
value: 1
---
name: config2
value: 2
"""
docs = pyrs_yaml.parse_all_docs(yaml_text)
print(len(docs)) # 2
print(docs[0].get("name")) # config1
9. NumPy ndarray サポート¶
オプション: NumPy が必要
pyrs-yaml は numpy.ndarray オブジェクトを直接 YAML にシリアライズできます。これは科学データ、モデルの重み、または多次元配列を人間が読める形式に保存するのに便利です。
import numpy as np
import pyrs_yaml
# 1-D array
arr = np.array([1, 2, 3], dtype="int32")
yaml_str = pyrs_yaml.safe_dump(arr)
print(yaml_str)
# - 1
# - 2
# - 3
# 2-D matrix
matrix = np.array([[1.0, 2.0], [3.0, 4.0]], dtype="float64")
yaml_str = pyrs_yaml.safe_dump(matrix)
print(yaml_str)
# -
# - 1.0
# - 2.0
# -
# - 3.0
# - 4.0
# Round-trip preserves values
loaded = pyrs_yaml.safe_load(yaml_str)
assert loaded == [[1.0, 2.0], [3.0, 4.0]]
サポートされる NumPy データ型¶
| NumPy dtype | YAML output | Notes |
|---|---|---|
int8/16/32/64 |
Plain integer | Quoted if negative |
uint8/16/32/64 |
Plain integer | — |
float32/64 |
Plain float | Quoted if negative |
complex64/128 |
(re+imj) string |
No native YAML complex type |
bool |
true / false |
— |
10. メタデータの操作(comment, anchor, tag)¶
doc = pyrs_yaml.parse("key: value")
node = doc.node().find("$.key")
node.set_comment("a note")
node.set_anchor("cfg")
node.set_tag("!custom")
print(doc.to_yaml())
# key: &cfg !custom value # a note
11. フォーマットの制御¶
doc = pyrs_yaml.parse("key: value")
doc.node().find("$.key").set_scalar_style("single_quoted")
12. スキーマで検証¶
Document.validate() は JSON Schema を受け取り、評価を
jsonschema に委譲します:
import pyrs_yaml
doc = pyrs_yaml.parse("port: 8080\ntags: [web, api]\n")
schema = {
"type": "object",
"properties": {"port": {"type": "integer"}},
"required": ["port"],
}
doc.validate(schema) # 合格
bad = pyrs_yaml.parse("tags: [web]\n")
bad.validate(schema)
# YamlValidateError: 'port' is a required property
評価器は別のインストールです
このパッケージが出荷するどれにも jsonschema は入っていません:pyrs-yaml は
typing-extensions のみに依存し、三つの extra は cli、pydantic、settings です。
検証の前に pip install jsonschema を実行してください。ライブラリだけで評価器のない環境では、
このステップのあらゆる validate() 呼び出しが、そのインストール経路を名乗り import エラーを
添えた YamlValidateError を投げます——スキーマなら通す文書でも同じです。評価器が出荷物に
無いことは既知の境界で、本リリースの欠陥ではありません。
テキストで与えたスキーマは YAML ではなく必ず JSON として読まれるため、
pyrs_yaml.parse("port: 8080\n").validate("type: object\nrequired: [port]\n") は
YamlValidateError を投げ、そのメッセージが引数として受け付ける形を名乗ります。dict か
JSON テキストを渡してください。
13. 高度な編集¶
doc.set_many({"$.items[*].active": False})
doc.sort_keys()
次のステップ¶
- 機能 — サポートされているすべての YAML 機能を探索
- パースガイド — 高度なパースオプション
- インプレース編集 — フォーマットを失わずにドキュメントを編集
- API リファレンス — 完全な API ドキュメント