summaryrefslogtreecommitdiffstats
path: root/_doc/dumpcls.ryd
blob: 048cdebde90ca0ee9ff2afc0fa57254a5b9b2b12 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
version: 0.2
text: md
pdf: false
# code_directory: ../_example
--- |
# Working with Python classes
 
## Dumping Python classes

Only `yaml = YAML(typ='unsafe')` loads and dumps Python objects
out-of-the-box. And since it loads **any** Python object, this can be
unsafe, so don't use it.

If you have instances of some class(es) that you want to dump or load,
it is easy to allow the YAML instance to do that explicitly. You can
either register the class with the `YAML` instance or decorate the
class.

Registering is done with `YAML.register_class()`:
--- !python |

import sys
import ruamel.yaml


class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age


yaml = ruamel.yaml.YAML()
yaml.register_class(User)
yaml.dump([User('Anthon', 18)], sys.stdout)
--- !stdout |
which gives as output::
--- |
The tag `!User` originates from the name of the class.

You can specify a different tag by adding the attribute `yaml_tag`, and
explicitly specify dump and/or load *classmethods* which have to be
named `to_yaml` resp. `from_yaml`:
--- !python |
import sys
import ruamel.yaml


class User:
    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):
        return cls(*node.value.split('-'))


yaml = ruamel.yaml.YAML()
yaml.register_class(User)
yaml.dump([User('Anthon', 18)], sys.stdout)
--- !stdout |
which gives as output::

--- |
When using the decorator, which takes the `YAML()` instance as a
parameter, the `yaml = YAML()` line needs to be moved up in the file:
--- !python |
import sys
from ruamel.yaml import YAML, yaml_object

yaml = YAML()


@yaml_object(yaml)
class User:
    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):
        return cls(*node.value.split('-'))


yaml.dump([User('Anthon', 18)], sys.stdout)

--- |
The `yaml_tag`, `from_yaml` and `to_yaml` work in the same way as when
using `.register_class()`.

Alternatively you can use the `register_class()` method as decorator,
This also requires you have the yaml instance available:
--- !python |
import sys
import ruamel.yaml

yaml = ruamel.yaml.YAML()

@yaml.register_class
class User:
    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):
        return cls(*node.value.split('-'))


yaml.dump([User('Anthon', 18)], sys.stdout)

--- !stdout |

This also gives:

--- |

If your class is dumped as a YAML mapping or sequence, there might be an (indirect)
reference to the object itself in one or more of the mapping keys (in YAML these
don't have to be simple scalars), mapping values or sequence entries.

That means that re-creating an object in `to_yaml` cannot generally just create
a `dict`/`list` from the `node` parameter and then create and return a complete
object. The solution for this is to create an empty object and yield that
and then fill in the content data afterwards. That way, if there is a self
reference, and the same node is encountered *while creating the content for the
object*, there is an `id` (from the yielded object) created for that node which
can be assigned.

--- !python |

from pathlib import Path
import ruamel.yaml

class Person:
    def __init__(self, name, siblings=None):
        self.name = name
        self.siblings = [] if siblings is None else siblings

arya = Person('Arya')   
sansa = Person('Sansa')
arya.siblings.append(sansa)  # there are better ways to represent this
sansa.siblings.append(arya)

yaml = ruamel.yaml.YAML()
yaml.register_class(Person)

path = Path('/tmp/arya.yaml')
yaml.dump(arya, path)
print(path.read_text())

--- !stdout |

dumping as:

--- |

And you can load the output:

--- !python |

from pathlib import Path
import ruamel.yaml

class Person:
    def __init__(self, name, siblings=None):
        self.name = name
        self.siblings = [] if siblings is None else siblings

    def __repr__(self):
        return f'Person(name: {self.name}, siblings: {self.siblings})'

path = Path('/tmp/arya.yaml')
yaml = ruamel.yaml.YAML()
yaml.register_class(Person)
data = yaml.load(path)

print(data)

--- !stdout |

giving:
--- |

But if you provide a (to) simple loader:

--- !python |

from pathlib import Path
import ruamel.yaml

class Person:
    def __init__(self, name, siblings=None):
        self.name = name
        self.siblings = [] if siblings is None else siblings

    def __repr__(self):
        return f'Person(name: {self.name}, siblings: {self.siblings})'

    @classmethod
    def from_yaml(cls, constructor, node):
        data = ruamel.yaml.CommentedMap()
        constructor.construct_mapping(node, maptyp=data, deep=True)
        return cls(**data)


path = Path('/tmp/arya.yaml')
yaml = ruamel.yaml.YAML()
yaml.register_class(Person)
data = yaml.load(path)
print(data)

--- !stdout |

giving:

--- |
As you can see, Sansa has no normal siblings after this load.

What you need to do is yield the empty Person instance and fill it in
afterwards:

--- !python |

from pathlib import Path
import ruamel.yaml

class Person:
    def __init__(self, name, siblings=None):
        self.name = name
        self.siblings = [] if siblings is None else siblings

    def __repr__(self):
        return f'Person(name: {self.name}, siblings: {self.siblings})'

    @classmethod
    def from_yaml(cls, constructor, node):
        person = Person(name='')
        yield person
        data = ruamel.yaml.CommentedMap()
        constructor.construct_mapping(node, maptyp=data, deep=True)
        for k, v in data.items():
            setattr(person, k, v)


path = Path('/tmp/arya.yaml')
yaml = ruamel.yaml.YAML()
yaml.register_class(Person)
data = yaml.load(path)
print(data)

--- !stdout |

giving:

--- |

## Dataclass

Although you could always register dataclasses, in 0.17.34 support was added to
call `__post_init__()` on these classes, if available.


--- !python |

from typing import ClassVar
from dataclasses import dataclass
import ruamel.yaml

@dataclass
class DC:
    yaml_tag: ClassVar = '!dc_example'   # if you don't want !DC as tag
    abc: int
    klm: int
    xyz: int = 0

    def __post_init__(self) -> None:
        self.xyz = self.abc + self.klm

yaml = ruamel.yaml.YAML()
yaml.register_class(DC)
dc = DC(abc=5, klm=42)
assert dc.xyz == 47

yaml_str = """\
!dc_example
abc: 13
klm: 37
"""
dc2 = yaml.load(yaml_str)
print(f'{dc2.xyz=}')

--- !stdout |
printing: