小编Rya*_*yan的帖子

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

我一直在阅读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 …

python yaml pyyaml ruamel.yaml

12
推荐指数
1
解决办法
502
查看次数

标签 统计

python ×1

pyyaml ×1

ruamel.yaml ×1

yaml ×1