【问题标题】:Loading custom objects with PyYAML使用 PyYAML 加载自定义对象
【发布时间】:2019-11-18 22:58:56
【问题描述】:

我有一个如下所示的 YAML 文件:

!!com.example.hero.YAMLAnimals
animals:
  Land: [Cow, Lion]
  Sea: [Salmon, Cod]

根据 PyYAML 文档,我应该能够通过子类化 yaml.YAMLOBJECT 来安全地加载 YAMLAnimals 对象。我试过这样做:

class YAMLAnimals(yaml.YAMLObject):
    yaml_tag = u'!com.example.hero.YAMLAnimals'

    def __init__(self, animals):
        self.animals = animals

但是,当我尝试使用 yaml.load()yaml.safe_load() 解析文件时,我收到以下错误:

could not determine a constructor for the tag 'tag:yaml.org,2002:com.example.hero.YAMLAnimals'

谢谢!

【问题讨论】:

  • 在文档中看到了这个:# In Python 3, do not use the 'u' prefix 另外,不是 YAML 专家,但在你的课堂上注意到你的字符串中只有一个 bang !
  • 可能是一个未解决的问题:github.com/yaml/pyyaml/issues/266

标签: python yaml pyyaml


【解决方案1】:

根据https://yaml.org/refcard.html!!<name> 被认为是二级标签(按照惯例,表示tag:yaml.org,2002:<name>)。因此,您应该将YAMLAnimals 中的yaml_tagu'!com.example.hero.YAMLAnimals' 更改为u'tag:yaml.org,2002:com.example.hero.YAMLAnimals',以便解析YAML 文件中的!!com.example.hero.YAMLAnimals 标签。

正如@mgrollins 所指出的,您应该将yaml.load 函数调用的Loader 指定为yaml.Loader 作为当前问题的临时解决方法(https://github.com/yaml/pyyaml/issues/266)[https://github.com/yaml/pyyaml/issues/266)

test.yaml

!!com.example.hero.YAMLAnimals
animals:
  Land: [Cow, Lion]
  Sea: [Salmon, Cod]

Python 代码:

import yaml

class YAMLAnimals(yaml.YAMLObject):
    yaml_tag = u'tag:yaml.org,2002:com.example.hero.YAMLAnimals'
    def __init__(self, animals):
        self.animals = animals

stream = open('test.yaml', 'r')
data = yaml.load(stream, Loader=yaml.Loader)
stream.close()
print(data.animals)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 2021-09-28
    相关资源
    最近更新 更多