如何使用锚点将 pydantic 模型导出到 yaml?

use*_*580 6 python yaml pydantic

我想将 Pydantic 模型导出到 YAML,但避免重复值并使用引用(锚+别名)。

这是一个例子:

from typing import List
from ruamel.yaml import YAML  # type: ignore
import yaml
from pydantic import BaseModel

class Author(BaseModel):
    id: str
    name: str
    age: int

class Book(BaseModel):
    id: str
    title: str
    author: Author

class Library(BaseModel):
    authors: List[Author]
    books: List[Book]


john_smith = Author(id="auth1", name="John Smith", age=42)

books = [
    Book(id="book1", title="Some title", author=john_smith),
    Book(id="book2", title="Another one", author=john_smith),
]

library = Library(authors=[john_smith], books=books)

print(yaml.dump(library.dict()))
Run Code Online (Sandbox Code Playgroud)

我得到:

authors:
- age: 42
  id: auth1
  name: John Smith
books:
- author:
    age: 42
    id: auth1
    name: John Smith
  id: book1
  title: Some title
- author:
    age: 42
    id: auth1
    name: John Smith
  id: book2
  title: Another one
Run Code Online (Sandbox Code Playgroud)

您可以看到每本书中的所有作者字段都是重复的。我想要使​​用锚点而不是复制所有信息的东西,如下所示:

authors:
- &auth1
  age: 42
  id: auth1
  name: John Smith
books:
- author: *auth1
  id: book1
  title: Some title
- author: *auth1
  id: book2
  title: Another one
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现这个目标?

Ant*_*hon 4

当你遍历一个嵌套的Python数据结构以对其进行转换时,你必须处理自引用的可能性,否则如果数据是自引用的,你的代码将陷入无限循环。

ruamel.yaml(和标准库json.dump())处理这个问题的方式是保留id()集合对象的列表(您想要递归的所有内容,所以不是像int, float,这样的基元str),如果这样的 anid()已经在列表中表示,该集合对象的第一次出现作为锚点,其他出现作为别名,因此您不必再次递归到该对象中(json.dump()告诉您它无法转储这样的结构,但至少它不会挂起)。

ruamel.yaml 中使用了相同的机制(跟踪id()s),以便在多个其他集合中引用同一集合时不会重复该集合。

pydantic 似乎没有这样做,因此在调用library.dict(). 我认为这就是为什么在文档中告诉您在 使用自引用数据将 pydanctic 转储到 JSON时要使用带有类名的字符串的原因

为了解决 pydantic 的这个限制,你可以做两件事:

  • 编写一个替代方案,.dict()返回一个转储为所需 YAML 文档格式的数据结构,这意味着它需要在多个位置返回具有相同数据 ( ) 的结构dict

  • 确保您可以使用 ruamel.yaml 直接转储类,这样您就不必转换它们。

但要使这两个功能都起作用,就要求您添加的作者book1book2添加后的作者相同,但事实并非如此。您不能安全地假设如果两个字典具有相同的键/值对,那么它们是相同的对象,因此任何比较都需要使用is而不是使用来完成==

在传入 的john_smith两次调用 后Book(),您没有.author指向相同数据的属性(即具有相同的id()):

from pydantic import BaseModel
from typing import List

class Author(BaseModel):
    id: str
    name: str
    age: int

class Book(BaseModel):
    id: str
    title: str
    author: Author

class Library(BaseModel):
    authors: List[Author]
    books: List[Book]


john_smith = Author(id="auth1", name="John Smith", age=42)

books = [
    Book(id="book1", title="Some title", author=john_smith),
    Book(id="book2", title="Another one", author=john_smith),
]

library = Library(authors=[john_smith], books=books)

print('same author?',  john_smith is library.books[0].author)
print('same author?',  library.books[0].author is library.books[1].author)
Run Code Online (Sandbox Code Playgroud)

这使:

same author? False
same author? False
Run Code Online (Sandbox Code Playgroud)

你可以做的是强制作者相同,然后使用比 pydantic 更聪明的东西.dict()

import sys
import ruamel.yaml


def gen_data(d, id_map=None):
    if id_map is None:
        id_map = {}
    d_id = id(d)
    if d_id in id_map:
        print('already found', id_map)
        return id_map[d_id]
    if isinstance(d, BaseModel):
        ret_val = {}
        for k, v in d:
            if k == 'author':
                print('auth', v, id(v))
            ret_val[k] = gen_data(v, id_map)
    elif isinstance(d, list):
        ret_val = []
        for elem in d:
            ret_val.append(gen_data(elem, id_map))
    else:
        return d  # should be primitive
    id_map[d_id] = ret_val
    return ret_val

# force authors to be the same
library.books[0].author = library.books[1].author = library.authors[0]
assert  library.books[0].author is library.books[1].author

# alternative for .dict()
data = gen_data(library)
    
yaml = ruamel.yaml.YAML()
yaml.dump(data, sys.stdout)
Run Code Online (Sandbox Code Playgroud)

这会产生你想要的结果:

auth id='auth1' name='John Smith' age=42 140494566559168
already found {140494566559168: {'id': 'auth1', 'name': 'John Smith', 'age': 42}, 140494576359168: [{'id': 'auth1', 'name': 'John Smith', 'age': 42}]}
auth id='auth1' name='John Smith' age=42 140494566559168
already found {140494566559168: {'id': 'auth1', 'name': 'John Smith', 'age': 42}, 140494576359168: [{'id': 'auth1', 'name': 'John Smith', 'age': 42}], 140494566559216: {'id': 'book1', 'title': 'Some title', 'author': {'id': 'auth1', 'name': 'John Smith', 'age': 42}}}
authors:
- &id001
  id: auth1
  name: John Smith
  age: 42
books:
- id: book1
  title: Some title
  author: *id001
- id: book2
  title: Another one
  author: *id001
Run Code Online (Sandbox Code Playgroud)

请注意,您不应该 import yaml,而应该实例化一个ruamel.yaml.YAML()实例。

如有必要,ruamel.yaml可以将锚点/别名的名称控制为id001.