如果您赶时间:从ruamel.yaml
0.15.19 开始,您可以使用一条语句注册类YAMLObject
,而无需子类化:
yaml = ruamel.yaml.YAML()
yaml.register_class(User)
它YAMLObject
是为了向后兼容 PyYAML,虽然它可能很方便,但我不推荐使用它,原因有以下三个:
- 它使您的类层次结构依赖于
YAMLObject
,正如您所注意到的,它可能会干扰其他依赖项
Loader
它默认使用不安全的
- 基于 Python 装饰器的解决方案将同样方便且侵入性更小。
子类化所做的唯一真实的事情YAMLObject
是注册一个constructor
for thatyaml_tag
和一个representer
for 子类。
所有示例都假设 from __future__ import print_function
您运行 Python 2。
如果您有以下情况,基于子类化YAMLObject
:
import sys
import ruamel.yaml
from ruamel.std.pathlib import Path
yaml = ruamel.yaml.YAML(typ='unsafe')
class User(ruamel.yaml.YAMLObject):
yaml_tag = u'user'
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def to_yaml(cls, representer, node):
return representer.represent_scalar(cls.yaml_tag,
u'{.name}-{.age}'.format(node, node))
@classmethod
def from_yaml(cls, constructor, node):
# type: (Any, Any) -> Any
return User(*node.value.split('-'))
data = {'users': [User('Anthon', 18)]}
yaml.dump(data, sys.stdout)
print()
tmp_file = Path('tmp.yaml')
yaml.dump(data, tmp_file)
rd = yaml.load(tmp_file)
print(rd['users'][0].name, rd['users'][0].age)
这会让你:
users: [!<user> Anthon-18]
Anthon 18
通过执行以下操作,您可以在不进行子类化的情况下获得完全相同的结果:
import sys
import ruamel.yaml
from ruamel.std.pathlib import Path
yaml = ruamel.yaml.YAML(typ='safe')
class User(object):
yaml_tag = u'user'
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def to_yaml(cls, representer, node):
return representer.represent_scalar(cls.yaml_tag,
u'{.name}-{.age}'.format(node, node))
@classmethod
def from_yaml(cls, constructor, node):
# type: (Any, Any) -> Any
return User(*node.value.split('-'))
yaml.representer.add_representer(User, User.to_yaml)
yaml.constructor.add_constructor(User.yaml_tag, User.from_yaml)
data = {'users': [User('Anthon', 18)]}
yaml.dump(data, sys.stdout)
print()
tmp_file = Path('tmp.yaml')
yaml.dump(data, tmp_file)
rd = yaml.load(tmp_file)
print(rd['users'][0].name, rd['users'][0].age)
上面使用了SafeLoader
(and SafeDumper
),这是朝着正确方向迈出的一步。但是XXXX.add_YYY
如果你有很多类,添加上面的行是很麻烦的,因为这些条目几乎但不完全相同。并且它不处理缺少任何一个或两者的类to_yaml
and from_yaml
。
要解决上述问题,我建议您yaml_object
在文件中创建一个装饰器和一个辅助类myyaml.py
:
import ruamel.yaml
yaml = ruamel.yaml.YAML(typ='safe')
class SafeYAMLObject(object):
def __init__(self, cls):
self._cls = cls
def to_yaml(self, representer, data):
return representer.represent_yaml_object(
self._cls.yaml_tag, data, self._cls,
flow_style=representer.default_flow_style)
def from_yaml(self, constructor, node):
return constructor.construct_yaml_object(node, self._cls)
def yaml_object(cls):
yaml.representer.add_representer(
cls, getattr(cls, 'to_yaml', SafeYAMLObject(cls).to_yaml))
yaml.constructor.add_constructor(
cls.yaml_tag, getattr(cls, 'from_yaml', SafeYAMLObject(cls).from_yaml))
return cls
有了它,你可以这样做:
import sys
from ruamel.std.pathlib import Path
from myyaml import yaml, yaml_object
@yaml_object
class User(object):
yaml_tag = u'user'
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def to_yaml(cls, representer, node):
return representer.represent_scalar(cls.yaml_tag,
u'{.name}-{.age}'.format(node, node))
@classmethod
def from_yaml(cls, constructor, node):
# type: (Any, Any) -> Any
return User(*node.value.split('-'))
data = {'users': [User('Anthon', 18)]}
yaml.dump(data, sys.stdout)
print()
tmp_file = Path('tmp.yaml')
yaml.dump(data, tmp_file)
rd = yaml.load(tmp_file)
print(rd['users'][0].name, rd['users'][0].age)
再次得到相同的结果。如果您删除to_yaml
andfrom_yaml
方法,您将获得相同的最终值,但 YAML 略有不同:
users:
- !<user> {age: 18, name: Anthon}
Anthon 18
我无法对此进行测试,但是使用此装饰器而不是子类化YAMLObject
应该可以摆脱以下TypeError
情况:
class SQLUser(Base, User):
¹
免责声明:我是ruamel.yaml
此答案中使用的软件包的作者。
免责声明 2:我并不是真正的 18 岁,但我确实遵循了 Brian Adams 在这张专辑的主打歌中表达的格言