为什么PyYAML使用生成器来构造对象?

Rya*_*yan 12 python yaml pyyaml ruamel.yaml

我一直在阅读PyYAML源代码,试图了解如何定义一个我可以添加的正确的构造函数add_constructor.我对该代码现在的工作方式有了很好的理解,但我仍然不明白为什么默认的YAML构造函数SafeConstructor是生成器.例如,该方法construct_yaml_mapSafeConstructor:

def construct_yaml_map(self, node):
    data = {}
    yield data
    value = self.construct_mapping(node)
    data.update(value)
Run Code Online (Sandbox Code Playgroud)

我理解如何使用生成器BaseConstructor.construct_object如下所示来存根一个对象,并且仅使用来自节点的数据填充它,如果deep=False传递给construct_mapping:

    if isinstance(data, types.GeneratorType):
        generator = data
        data = generator.next()
        if self.deep_construct:
            for dummy in generator:
                pass
        else:
            self.state_generators.append(generator)
Run Code Online (Sandbox Code Playgroud)

我理解BaseConstructor.construct_documentdeep=Falsefor 的情况下如何生成数据construct_mapping.

def construct_document(self, node):
    data = self.construct_object(node)
    while self.state_generators:
        state_generators = self.state_generators
        self.state_generators = []
        for generator in state_generators:
            for dummy in generator:
                pass
Run Code Online (Sandbox Code Playgroud)

我不明白的是通过遍历生成器来截断数据对象和解决对象的好处construct_document.是否必须这样做以支持YAML规范中的某些内容,或者它是否提供了性能优势?

关于另一个问题的答案有点帮助,但我不明白为什么答案会这样做:

def foo_constructor(loader, node):
    instance = Foo.__new__(Foo)
    yield instance
    state = loader.construct_mapping(node, deep=True)
    instance.__init__(**state)
Run Code Online (Sandbox Code Playgroud)

而不是这个:

def foo_constructor(loader, node):
    state = loader.construct_mapping(node, deep=True)
    return Foo(**state)
Run Code Online (Sandbox Code Playgroud)

我已经测试过后一种形式适用于其他答案上发布的示例,但也许我错过了一些边缘案例.

我使用的是PyYAML的3.10版本,但看起来有问题的代码在PyYAML的最新版本(3.12)中是相同的.

Ant*_*hon 10

在YAML中,您可以拥有锚点和别名.有了它,你可以直接或间接地建立自我参照结构.

如果YAML没有这种自引用的可能性,你可以先构建所有子节点,然后一次创建父结构.但是由于自我引用,你可能没有让孩子"填写"你正在创建的结构.通过使用生成器的两步过程(我称之为两步,因为它在到达方法结束之前只有一个产量),您可以部分创建一个对象并用自引用填充它,因为对象存在(即它在内存中的位置是定义的).

好处不在于速度,而在于纯粹因为自我引用成为可能.

如果您从答案中简化示例,请参考以下内容:

import sys
import ruamel.yaml as yaml


class Foo(object):
    def __init__(self, s, l=None, d=None):
        self.s = s
        self.l1, self.l2 = l
        self.d = d


def foo_constructor(loader, node):
    instance = Foo.__new__(Foo)
    yield instance
    state = loader.construct_mapping(node, deep=True)
    instance.__init__(**state)

yaml.add_constructor(u'!Foo', foo_constructor)

x = yaml.load('''
&fooref
!Foo
s: *fooref
l: [1, 2]
d: {try: this}
''', Loader=yaml.Loader)

yaml.dump(x, sys.stdout)
Run Code Online (Sandbox Code Playgroud)

但如果你foo_constructor()改为:

def foo_constructor(loader, node):
    instance = Foo.__new__(Foo)
    state = loader.construct_mapping(node, deep=True)
    instance.__init__(**state)
    return instance
Run Code Online (Sandbox Code Playgroud)

(收益率被删除,添加了最终的回报),你得到一个ConstructorError:带有消息

found unconstructable recursive node 
  in "<unicode string>", line 2, column 1:
    &fooref
Run Code Online (Sandbox Code Playgroud)

PyYAML应该给出类似的信息.检查该错误的回溯,您可以看到ruamel.yaml/PyYAML尝试在源代码中解析别名的位置.