问题描述
我一直在阅读 pyyaml 源代码,试图了解如何定义一个合适的构造函数,我可以使用 add_constructor 添加该构造函数.我现在对该代码的工作原理有了很好的理解,但我仍然不明白为什么 safeconstructor 中的默认 yaml 构造函数是生成器.比如safeconstructor的方法construct_yaml_map:
i've been reading the pyyaml source code to try to understand how to define a proper constructor function that i can add with add_constructor. i have a pretty good understanding of how that code works now, but i still don't understand why the default yaml constructors in the safeconstructor are generators. for example, the method construct_yaml_map of safeconstructor:
def construct_yaml_map(self, node): data = {} yield data value = self.construct_mapping(node) data.update(value)
我了解生成器如何在 baseconstructor.construct_object 中使用,如下所示以存根一个对象,并且仅在传递 deep=false 时使用来自节点的数据填充它construct_mapping:
i understand how the generator is used in baseconstructor.construct_object as follows to stub out an object and only populate it with data from the node if deep=false is passed to 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)
并且我了解在 deep=false for construct_mapping 的情况下如何在 baseconstructor.construct_document 中生成数据.
and i understand how the data is generated in baseconstructor.construct_document in the case where deep=false for 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
我不明白的是,将数据对象存根并通过迭代 construct_document 中的生成器来处理对象的好处.是否必须这样做以支持 yaml 规范中的某些内容,还是提供性能优势?
what i don't understand is the benefit of stubbing out the data objects and working down through the objects by iterating over the generators in construct_document. does this have to be done to support something in the yaml spec, or does it provide a performance benefit?
这个关于另一个问题的答案有点帮助,但我不明白为什么这个答案会这样:
this answer on another question was somewhat helpful, but i don't understand why that answer does this:
def foo_constructor(loader, node): instance = foo.__new__(foo) yield instance state = loader.construct_mapping(node, deep=true) instance.__init__(**state)
而不是这个:
def foo_constructor(loader, node): state = loader.construct_mapping(node, deep=true) return foo(**state)
我已经测试过后一种形式适用于发布在另一个答案上的示例,但也许我错过了一些极端情况.
i've tested that the latter form works for the examples posted on that other answer, but perhaps i am missing some edge case.
我使用的是 3.10 版的 pyyaml,但看起来有问题的代码在最新版 (3.12) 的 pyyaml 中是相同的.
i am using version 3.10 of pyyaml, but it looks like the code in question is the same in the latest version (3.12) of pyyaml.
推荐答案
在 yaml 中你可以有 锚和别名.有了它,您可以直接或间接地创建自引用结构.
in yaml you can have anchors and aliases. with that you can make self-referential structures, directly or indirectly.
如果 yaml 没有这种自引用的可能性,您可以先构造所有子结构,然后一次性创建父结构.但是由于自我引用,您可能还没有孩子来填写"您正在创建的结构.通过使用生成器的两步过程(我称之为两步,因为在方法结束之前它只有一个yield),您可以部分创建一个对象并用自引用填充它,因为对象存在(即它在内存中的位置已定义).
if yaml would not have this possibility of self-reference, you could just first construct all the children and then create the parent structure in one go. but because of the self-references you might not have the child yet to "fill-out" the structure that you are creating. by using the two-step process of the generator (i call this two step, because it has only one yield before you come to the end of the method), you can create an object partially and the fill it out with a self-reference, because the object exist (i.e. its place in memory is defined).
好处不在于速度,而纯粹是因为使自引用成为可能.
the benefit is not in speed, but purely because of making the self-reference possible.
如果您从您引用的答案中简化示例,则会加载以下内容:
if you simplify the example from the answer you refer to a bit, the following loads:
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)
但如果你将 foo_constructor() 更改为:
but if you change foo_constructor() to:
def foo_constructor(loader, node): instance = foo.__new__(foo) state = loader.construct_mapping(node, deep=true) instance.__init__(**state) return instance
(yield 被移除,添加了最终返回),你会得到一个 constructorerror: with as message
(yield removed, added a final return), you get a constructorerror: with as message
found unconstructable recursive node in "", line 2, column 1: &fooref
pyyaml 应该给出类似的消息.检查该错误的回溯,您可以看到 ruamel.yaml/pyyaml 尝试在源代码中解析别名的位置.
pyyaml should give a similar message. inspect the traceback on that error and you can see where ruamel.yaml/pyyaml tries to resolve the alias in the source code.