If you are in a hurry: as of ruamel.yaml
0.15.19 you can register classes with one statement, without subclassing of YAMLObject
:
yaml = ruamel.yaml.YAML()
yaml.register_class(User)
The YAMLObject
is there for backwards compatibility with PyYAML, and although it might be convenient, I cannot really recommend using it for three reasons:
- It makes your class hierarchy dependent on
YAMLObject
, which, as you noticed, can interfere with other dependencies
- It uses the unsafe
Loader
by default
- A solution based on Python decorators would be as convenient and much less intrusive.
The only real thing that subclassing YAMLObject
does is registering a constructor
for that yaml_tag
and a representer
for subclass.
All examples assume from __future__ import print_function
if you run Python 2.
If you have the following, based on subclassing 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)
that will get you:
users: [!<user> Anthon-18]
Anthon 18
You can get the exact same result without subclassing, by doing:
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)
The above uses the SafeLoader
(and SafeDumper
), which is a step in the right direction. But adding the XXXX.add_YYY
lines above is nuisance if you have a lot of classes, as those entries are almost, but not quite, the same. And it doesn't handle classes missing either or both to_yaml
and from_yaml
.
To solve the above I suggest you make a decorator yaml_object
and a helper class in a file 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
Having that you can do:
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)
again with the same result. If you remove the to_yaml
and from_yaml
methods, you would the same final value, but slightly different YAML:
users:
- !<user> {age: 18, name: Anthon}
Anthon 18
I have not been able to test this, but using this decorator instead of subclassing YAMLObject
should get rid of the TypeError
when doing:
class SQLUser(Base, User):
¹
Disclaimer: I am the author of the ruamel.yaml
package used in this answer.
Disclaimer 2: I am not really 18, but I do follow Brian Adams' adagium expressed in the title song of this album
YAMLObject
to be able to dumpUser
. Subclassing is IMO the most intrusive way of enabling dumping and loading. And yourUser
class probably doesn't work because it doesn't have ayaml_tag
. Are you open to removing the dependency onYAMLObject
?yaml_tag
but it's there. I edited my question. TheUser
class works correctly by itself (I implemented theto_yaml
method to enable the class to be dumped correctly into YAML files). I'm open to everything, but in this way I can dump the object as I wish in a transparent way to the end-user. Just ayaml.dump
works as expected...ruamel.yaml
. I am not sure which of the solutions in my answer you actually used, but registering should work for you, decorating might still interfere because of the wrapping that it does.