Debian Codegraph @

strictyaml/ruamel/main.py

raw
1 # coding: utf-8
2
3 from __future__ import absolute_import, unicode_literals, print_function
4
5 import sys
6 import os
7 import warnings
8 import glob
9 from importlib import import_module
10
11
12 import strictyaml.ruamel
13 from strictyaml.ruamel.error import UnsafeLoaderWarning, YAMLError # NOQA
14
15 from strictyaml.ruamel.tokens import * # NOQA
16 from strictyaml.ruamel.events import * # NOQA
17 from strictyaml.ruamel.nodes import * # NOQA
18
19 from strictyaml.ruamel.loader import (
20 BaseLoader,
21 SafeLoader,
22 Loader,
23 RoundTripLoader,
24 ) # NOQA
25 from strictyaml.ruamel.dumper import (
26 BaseDumper,
27 SafeDumper,
28 Dumper,
29 RoundTripDumper,
30 ) # NOQA
31 from strictyaml.ruamel.compat import StringIO, BytesIO, with_metaclass, PY3, nprint
32 from strictyaml.ruamel.resolver import VersionedResolver, Resolver # NOQA
33 from strictyaml.ruamel.representer import (
34 BaseRepresenter,
35 SafeRepresenter,
36 Representer,
37 RoundTripRepresenter,
38 )
39 from strictyaml.ruamel.constructor import (
40 BaseConstructor,
41 SafeConstructor,
42 Constructor,
43 RoundTripConstructor,
44 )
45 from strictyaml.ruamel.loader import Loader as UnsafeLoader
46
47 if False: # MYPY
48 from typing import List, Set, Dict, Union, Any, Callable, Optional, Text # NOQA
49 from strictyaml.ruamel.compat import StreamType, StreamTextType, VersionType # NOQA
50
51 if PY3:
52 from pathlib import Path
53 else:
54 Path = Any
55
56 try:
57 from _ruamel_yaml import CParser, CEmitter # type: ignore
58 except: # NOQA
59 CParser = CEmitter = None
60
61 # import io
62
63 enforce = object()
64
65
66 # YAML is an acronym, i.e. spoken: rhymes with "camel". And thus a
67 # subset of abbreviations, which should be all caps according to PEP8
68
69
70 class YAML(object):
71 def __init__(
72 self,
73 _kw=enforce,
74 typ=None,
75 pure=False,
76 output=None,
77 plug_ins=None, # input=None,
78 ):
79 # type: (Any, Optional[Text], Any, Any, Any) -> None
80 """
81 _kw: not used, forces keyword arguments in 2.7 (in 3 you can do (*, safe_load=..)
82 typ: 'rt'/None -> RoundTripLoader/RoundTripDumper, (default)
83 'safe' -> SafeLoader/SafeDumper,
84 'unsafe' -> normal/unsafe Loader/Dumper
85 'base' -> baseloader
86 pure: if True only use Python modules
87 input/output: needed to work as context manager
88 plug_ins: a list of plug-in files
89 """
90 if _kw is not enforce:
91 raise TypeError(
92 "{}.__init__() takes no positional argument but at least "
93 "one was given ({!r})".format(self.__class__.__name__, _kw)
94 )
95
96 self.typ = ["rt"] if typ is None else (typ if isinstance(typ, list) else [typ])
97 self.pure = pure
98
99 # self._input = input
100 self._output = output
101 self._context_manager = None # type: Any
102
103 self.plug_ins = [] # type: List[Any]
104 for pu in ([] if plug_ins is None else plug_ins) + self.official_plug_ins():
105 file_name = pu.replace(os.sep, ".")
106 self.plug_ins.append(import_module(file_name))
107 self.Resolver = strictyaml.ruamel.resolver.VersionedResolver # type: Any
108 self.allow_unicode = True
109 self.Reader = None # type: Any
110 self.Representer = None # type: Any
111 self.Constructor = None # type: Any
112 self.Scanner = None # type: Any
113 self.Serializer = None # type: Any
114 self.default_flow_style = None # type: Any
115 typ_found = 1
116 setup_rt = False
117 if "rt" in self.typ:
118 setup_rt = True
119 elif "safe" in self.typ:
120 self.Emitter = (
121 strictyaml.ruamel.emitter.Emitter
122 if pure or CEmitter is None
123 else CEmitter
124 )
125 self.Representer = strictyaml.ruamel.representer.SafeRepresenter
126 self.Parser = (
127 strictyaml.ruamel.parser.Parser if pure or CParser is None else CParser
128 )
129 self.Composer = strictyaml.ruamel.composer.Composer
130 self.Constructor = strictyaml.ruamel.constructor.SafeConstructor
131 elif "base" in self.typ:
132 self.Emitter = strictyaml.ruamel.emitter.Emitter
133 self.Representer = strictyaml.ruamel.representer.BaseRepresenter
134 self.Parser = (
135 strictyaml.ruamel.parser.Parser if pure or CParser is None else CParser
136 )
137 self.Composer = strictyaml.ruamel.composer.Composer
138 self.Constructor = strictyaml.ruamel.constructor.BaseConstructor
139 elif "unsafe" in self.typ:
140 self.Emitter = (
141 strictyaml.ruamel.emitter.Emitter
142 if pure or CEmitter is None
143 else CEmitter
144 )
145 self.Representer = strictyaml.ruamel.representer.Representer
146 self.Parser = (
147 strictyaml.ruamel.parser.Parser if pure or CParser is None else CParser
148 )
149 self.Composer = strictyaml.ruamel.composer.Composer
150 self.Constructor = strictyaml.ruamel.constructor.Constructor
151 else:
152 setup_rt = True
153 typ_found = 0
154 if setup_rt:
155 self.default_flow_style = False
156 # no optimized rt-dumper yet
157 self.Emitter = strictyaml.ruamel.emitter.Emitter
158 self.Serializer = strictyaml.ruamel.serializer.Serializer
159 self.Representer = strictyaml.ruamel.representer.RoundTripRepresenter
160 self.Scanner = strictyaml.ruamel.scanner.RoundTripScanner
161 # no optimized rt-parser yet
162 self.Parser = strictyaml.ruamel.parser.RoundTripParser
163 self.Composer = strictyaml.ruamel.composer.Composer
164 self.Constructor = strictyaml.ruamel.constructor.RoundTripConstructor
165 del setup_rt
166 self.stream = None
167 self.canonical = None
168 self.old_indent = None
169 self.width = None
170 self.line_break = None
171
172 self.map_indent = None
173 self.sequence_indent = None
174 self.sequence_dash_offset = 0
175 self.compact_seq_seq = None
176 self.compact_seq_map = None
177 self.sort_base_mapping_type_on_output = None # default: sort
178
179 self.top_level_colon_align = None
180 self.prefix_colon = None
181 self.version = None
182 self.preserve_quotes = None
183 self.allow_duplicate_keys = False # duplicate keys in map, set
184 self.encoding = "utf-8"
185 self.explicit_start = None
186 self.explicit_end = None
187 self.tags = None
188 self.default_style = None
189 self.top_level_block_style_scalar_no_indent_error_1_1 = False
190 # directives end indicator with single scalar document
191 self.scalar_after_indicator = None
192 # [a, b: 1, c: {d: 2}] vs. [a, {b: 1}, {c: {d: 2}}]
193 self.brace_single_entry_mapping_in_flow_sequence = False
194 for module in self.plug_ins:
195 if getattr(module, "typ", None) in self.typ:
196 typ_found += 1
197 module.init_typ(self)
198 break
199 if typ_found == 0:
200 raise NotImplementedError(
201 'typ "{}"not recognised (need to install plug-in?)'.format(self.typ)
202 )
203
204 @property
205 def reader(self):
206 # type: () -> Any
207 try:
208 return self._reader # type: ignore
209 except AttributeError:
210 self._reader = self.Reader(None, loader=self)
211 return self._reader
212
213 @property
214 def scanner(self):
215 # type: () -> Any
216 try:
217 return self._scanner # type: ignore
218 except AttributeError:
219 self._scanner = self.Scanner(loader=self)
220 return self._scanner
221
222 @property
223 def parser(self):
224 # type: () -> Any
225 attr = "_" + sys._getframe().f_code.co_name
226 if not hasattr(self, attr):
227 if self.Parser is not CParser:
228 setattr(self, attr, self.Parser(loader=self))
229 else:
230 if getattr(self, "_stream", None) is None:
231 # wait for the stream
232 return None
233 else:
234 # if not hasattr(self._stream, 'read') and hasattr(self._stream, 'open'):
235 # # pathlib.Path() instance
236 # setattr(self, attr, CParser(self._stream))
237 # else:
238 setattr(self, attr, CParser(self._stream))
239 # self._parser = self._composer = self
240 # nprint('scanner', self.loader.scanner)
241
242 return getattr(self, attr)
243
244 @property
245 def composer(self):
246 # type: () -> Any
247 attr = "_" + sys._getframe().f_code.co_name
248 if not hasattr(self, attr):
249 setattr(self, attr, self.Composer(loader=self))
250 return getattr(self, attr)
251
252 @property
253 def constructor(self):
254 # type: () -> Any
255 attr = "_" + sys._getframe().f_code.co_name
256 if not hasattr(self, attr):
257 cnst = self.Constructor(preserve_quotes=self.preserve_quotes, loader=self)
258 cnst.allow_duplicate_keys = self.allow_duplicate_keys
259 setattr(self, attr, cnst)
260 return getattr(self, attr)
261
262 @property
263 def resolver(self):
264 # type: () -> Any
265 attr = "_" + sys._getframe().f_code.co_name
266 if not hasattr(self, attr):
267 setattr(self, attr, self.Resolver(version=self.version, loader=self))
268 return getattr(self, attr)
269
270 @property
271 def emitter(self):
272 # type: () -> Any
273 attr = "_" + sys._getframe().f_code.co_name
274 if not hasattr(self, attr):
275 if self.Emitter is not CEmitter:
276 _emitter = self.Emitter(
277 None,
278 canonical=self.canonical,
279 indent=self.old_indent,
280 width=self.width,
281 allow_unicode=self.allow_unicode,
282 line_break=self.line_break,
283 prefix_colon=self.prefix_colon,
284 brace_single_entry_mapping_in_flow_sequence=self.brace_single_entry_mapping_in_flow_sequence, # NOQA
285 dumper=self,
286 )
287 setattr(self, attr, _emitter)
288 if self.map_indent is not None:
289 _emitter.best_map_indent = self.map_indent
290 if self.sequence_indent is not None:
291 _emitter.best_sequence_indent = self.sequence_indent
292 if self.sequence_dash_offset is not None:
293 _emitter.sequence_dash_offset = self.sequence_dash_offset
294 # _emitter.block_seq_indent = self.sequence_dash_offset
295 if self.compact_seq_seq is not None:
296 _emitter.compact_seq_seq = self.compact_seq_seq
297 if self.compact_seq_map is not None:
298 _emitter.compact_seq_map = self.compact_seq_map
299 else:
300 if getattr(self, "_stream", None) is None:
301 # wait for the stream
302 return None
303 return None
304 return getattr(self, attr)
305
306 @property
307 def serializer(self):
308 # type: () -> Any
309 attr = "_" + sys._getframe().f_code.co_name
310 if not hasattr(self, attr):
311 setattr(
312 self,
313 attr,
314 self.Serializer(
315 encoding=self.encoding,
316 explicit_start=self.explicit_start,
317 explicit_end=self.explicit_end,
318 version=self.version,
319 tags=self.tags,
320 dumper=self,
321 ),
322 )
323 return getattr(self, attr)
324
325 @property
326 def representer(self):
327 # type: () -> Any
328 attr = "_" + sys._getframe().f_code.co_name
329 if not hasattr(self, attr):
330 repres = self.Representer(
331 default_style=self.default_style,
332 default_flow_style=self.default_flow_style,
333 dumper=self,
334 )
335 if self.sort_base_mapping_type_on_output is not None:
336 repres.sort_base_mapping_type_on_output = (
337 self.sort_base_mapping_type_on_output
338 )
339 setattr(self, attr, repres)
340 return getattr(self, attr)
341
342 # separate output resolver?
343
344 # def load(self, stream=None):
345 # if self._context_manager:
346 # if not self._input:
347 # raise TypeError("Missing input stream while dumping from context manager")
348 # for data in self._context_manager.load():
349 # yield data
350 # return
351 # if stream is None:
352 # raise TypeError("Need a stream argument when not loading from context manager")
353 # return self.load_one(stream)
354
355 def load(self, stream):
356 # type: (Union[Path, StreamTextType]) -> Any
357 """
358 at this point you either have the non-pure Parser (which has its own reader and
359 scanner) or you have the pure Parser.
360 If the pure Parser is set, then set the Reader and Scanner, if not already set.
361 If either the Scanner or Reader are set, you cannot use the non-pure Parser,
362 so reset it to the pure parser and set the Reader resp. Scanner if necessary
363 """
364 if not hasattr(stream, "read") and hasattr(stream, "open"):
365 # pathlib.Path() instance
366 with stream.open("rb") as fp:
367 return self.load(fp)
368 constructor, parser = self.get_constructor_parser(stream)
369 try:
370 return constructor.get_single_data()
371 finally:
372 parser.dispose()
373 try:
374 self._reader.reset_reader()
375 except AttributeError:
376 pass
377 try:
378 self._scanner.reset_scanner()
379 except AttributeError:
380 pass
381
382 def load_all(self, stream, _kw=enforce): # , skip=None):
383 # type: (Union[Path, StreamTextType], Any) -> Any
384 if _kw is not enforce:
385 raise TypeError(
386 "{}.__init__() takes no positional argument but at least "
387 "one was given ({!r})".format(self.__class__.__name__, _kw)
388 )
389 if not hasattr(stream, "read") and hasattr(stream, "open"):
390 # pathlib.Path() instance
391 with stream.open("r") as fp:
392 for d in self.load_all(fp, _kw=enforce):
393 yield d
394 return
395 # if skip is None:
396 # skip = []
397 # elif isinstance(skip, int):
398 # skip = [skip]
399 constructor, parser = self.get_constructor_parser(stream)
400 try:
401 while constructor.check_data():
402 yield constructor.get_data()
403 finally:
404 parser.dispose()
405 try:
406 self._reader.reset_reader()
407 except AttributeError:
408 pass
409 try:
410 self._scanner.reset_scanner()
411 except AttributeError:
412 pass
413
414 def get_constructor_parser(self, stream):
415 # type: (StreamTextType) -> Any
416 """
417 the old cyaml needs special setup, and therefore the stream
418 """
419 if self.Parser is not CParser:
420 if self.Reader is None:
421 self.Reader = strictyaml.ruamel.reader.Reader
422 if self.Scanner is None:
423 self.Scanner = strictyaml.ruamel.scanner.Scanner
424 self.reader.stream = stream
425 else:
426 if self.Reader is not None:
427 if self.Scanner is None:
428 self.Scanner = strictyaml.ruamel.scanner.Scanner
429 self.Parser = strictyaml.ruamel.parser.Parser
430 self.reader.stream = stream
431 elif self.Scanner is not None:
432 if self.Reader is None:
433 self.Reader = strictyaml.ruamel.reader.Reader
434 self.Parser = strictyaml.ruamel.parser.Parser
435 self.reader.stream = stream
436 else:
437 # combined C level reader>scanner>parser
438 # does some calls to the resolver, e.g. BaseResolver.descend_resolver
439 # if you just initialise the CParser, to much of resolver.py
440 # is actually used
441 rslvr = self.Resolver
442 # if rslvr is strictyaml.ruamel.resolver.VersionedResolver:
443 # rslvr = strictyaml.ruamel.resolver.Resolver
444
445 class XLoader(self.Parser, self.Constructor, rslvr): # type: ignore
446 def __init__(
447 selfx, stream, version=self.version, preserve_quotes=None
448 ):
449 # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None # NOQA
450 CParser.__init__(selfx, stream)
451 selfx._parser = selfx._composer = selfx
452 self.Constructor.__init__(selfx, loader=selfx)
453 selfx.allow_duplicate_keys = self.allow_duplicate_keys
454 rslvr.__init__(selfx, version=version, loadumper=selfx)
455
456 self._stream = stream
457 loader = XLoader(stream)
458 return loader, loader
459 return self.constructor, self.parser
460
461 def dump(self, data, stream=None, _kw=enforce, transform=None):
462 # type: (Any, Union[Path, StreamType], Any, Any) -> Any
463 if self._context_manager:
464 if not self._output:
465 raise TypeError(
466 "Missing output stream while dumping from context manager"
467 )
468 if _kw is not enforce:
469 raise TypeError(
470 "{}.dump() takes one positional argument but at least "
471 "two were given ({!r})".format(self.__class__.__name__, _kw)
472 )
473 if transform is not None:
474 raise TypeError(
475 "{}.dump() in the context manager cannot have transform keyword "
476 "".format(self.__class__.__name__)
477 )
478 self._context_manager.dump(data)
479 else: # old style
480 if stream is None:
481 raise TypeError(
482 "Need a stream argument when not dumping from context manager"
483 )
484 return self.dump_all([data], stream, _kw, transform=transform)
485
486 def dump_all(self, documents, stream, _kw=enforce, transform=None):
487 # type: (Any, Union[Path, StreamType], Any, Any) -> Any
488 if self._context_manager:
489 raise NotImplementedError
490 if _kw is not enforce:
491 raise TypeError(
492 "{}.dump(_all) takes two positional argument but at least "
493 "three were given ({!r})".format(self.__class__.__name__, _kw)
494 )
495 self._output = stream
496 self._context_manager = YAMLContextManager(self, transform=transform)
497 for data in documents:
498 self._context_manager.dump(data)
499 self._context_manager.teardown_output()
500 self._output = None
501 self._context_manager = None
502
503 def Xdump_all(self, documents, stream, _kw=enforce, transform=None):
504 # type: (Any, Union[Path, StreamType], Any, Any) -> Any
505 """
506 Serialize a sequence of Python objects into a YAML stream.
507 """
508 if not hasattr(stream, "write") and hasattr(stream, "open"):
509 # pathlib.Path() instance
510 with stream.open("w") as fp:
511 return self.dump_all(documents, fp, _kw, transform=transform)
512 if _kw is not enforce:
513 raise TypeError(
514 "{}.dump(_all) takes two positional argument but at least "
515 "three were given ({!r})".format(self.__class__.__name__, _kw)
516 )
517 # The stream should have the methods `write` and possibly `flush`.
518 if self.top_level_colon_align is True:
519 tlca = max([len(str(x)) for x in documents[0]]) # type: Any
520 else:
521 tlca = self.top_level_colon_align
522 if transform is not None:
523 fstream = stream
524 if self.encoding is None:
525 stream = StringIO()
526 else:
527 stream = BytesIO()
528 serializer, representer, emitter = self.get_serializer_representer_emitter(
529 stream, tlca
530 )
531 try:
532 self.serializer.open()
533 for data in documents:
534 try:
535 self.representer.represent(data)
536 except AttributeError:
537 # nprint(dir(dumper._representer))
538 raise
539 self.serializer.close()
540 finally:
541 try:
542 self.emitter.dispose()
543 except AttributeError:
544 raise
545 # self.dumper.dispose() # cyaml
546 delattr(self, "_serializer")
547 delattr(self, "_emitter")
548 if transform:
549 val = stream.getvalue()
550 if self.encoding:
551 val = val.decode(self.encoding)
552 if fstream is None:
553 transform(val)
554 else:
555 fstream.write(transform(val))
556 return None
557
558 def get_serializer_representer_emitter(self, stream, tlca):
559 # type: (StreamType, Any) -> Any
560 # we have only .Serializer to deal with (vs .Reader & .Scanner), much simpler
561 if self.Emitter is not CEmitter:
562 if self.Serializer is None:
563 self.Serializer = strictyaml.ruamel.serializer.Serializer
564 self.emitter.stream = stream
565 self.emitter.top_level_colon_align = tlca
566 if self.scalar_after_indicator is not None:
567 self.emitter.scalar_after_indicator = self.scalar_after_indicator
568 return self.serializer, self.representer, self.emitter
569 if self.Serializer is not None:
570 # cannot set serializer with CEmitter
571 self.Emitter = strictyaml.ruamel.emitter.Emitter
572 self.emitter.stream = stream
573 self.emitter.top_level_colon_align = tlca
574 if self.scalar_after_indicator is not None:
575 self.emitter.scalar_after_indicator = self.scalar_after_indicator
576 return self.serializer, self.representer, self.emitter
577 # C routines
578
579 rslvr = (
580 strictyaml.ruamel.resolver.BaseResolver
581 if "base" in self.typ
582 else strictyaml.ruamel.resolver.Resolver
583 )
584
585 class XDumper(CEmitter, self.Representer, rslvr): # type: ignore
586 def __init__(
587 selfx,
588 stream,
589 default_style=None,
590 default_flow_style=None,
591 canonical=None,
592 indent=None,
593 width=None,
594 allow_unicode=None,
595 line_break=None,
596 encoding=None,
597 explicit_start=None,
598 explicit_end=None,
599 version=None,
600 tags=None,
601 block_seq_indent=None,
602 top_level_colon_align=None,
603 prefix_colon=None,
604 ):
605 # type: (StreamType, Any, Any, Any, Optional[bool], Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Any, Any, Any, Any, Any) -> None # NOQA
606 CEmitter.__init__(
607 selfx,
608 stream,
609 canonical=canonical,
610 indent=indent,
611 width=width,
612 encoding=encoding,
613 allow_unicode=allow_unicode,
614 line_break=line_break,
615 explicit_start=explicit_start,
616 explicit_end=explicit_end,
617 version=version,
618 tags=tags,
619 )
620 selfx._emitter = selfx._serializer = selfx._representer = selfx
621 self.Representer.__init__(
622 selfx,
623 default_style=default_style,
624 default_flow_style=default_flow_style,
625 )
626 rslvr.__init__(selfx)
627
628 self._stream = stream
629 dumper = XDumper(
630 stream,
631 default_style=self.default_style,
632 default_flow_style=self.default_flow_style,
633 canonical=self.canonical,
634 indent=self.old_indent,
635 width=self.width,
636 allow_unicode=self.allow_unicode,
637 line_break=self.line_break,
638 explicit_start=self.explicit_start,
639 explicit_end=self.explicit_end,
640 version=self.version,
641 tags=self.tags,
642 )
643 self._emitter = self._serializer = dumper
644 return dumper, dumper, dumper
645
646 # basic types
647 def map(self, **kw):
648 # type: (Any) -> Any
649 if "rt" in self.typ:
650 from strictyaml.ruamel.comments import CommentedMap
651
652 return CommentedMap(**kw)
653 else:
654 return dict(**kw)
655
656 def seq(self, *args):
657 # type: (Any) -> Any
658 if "rt" in self.typ:
659 from strictyaml.ruamel.comments import CommentedSeq
660
661 return CommentedSeq(*args)
662 else:
663 return list(*args)
664
665 # helpers
666 def official_plug_ins(self):
667 # type: () -> Any
668 bd = os.path.dirname(__file__)
669 gpbd = os.path.dirname(os.path.dirname(bd))
670 res = [x.replace(gpbd, "")[1:-3] for x in glob.glob(bd + "/*/__plug_in__.py")]
671 return res
672
673 def register_class(self, cls):
674 # type:(Any) -> Any
675 """
676 register a class for dumping loading
677 - if it has attribute yaml_tag use that to register, else use class name
678 - if it has methods to_yaml/from_yaml use those to dump/load else dump attributes
679 as mapping
680 """
681 tag = getattr(cls, "yaml_tag", "!" + cls.__name__)
682 try:
683 self.representer.add_representer(cls, cls.to_yaml)
684 except AttributeError:
685
686 def t_y(representer, data):
687 # type: (Any, Any) -> Any
688 return representer.represent_yaml_object(
689 tag, data, cls, flow_style=representer.default_flow_style
690 )
691
692 self.representer.add_representer(cls, t_y)
693 try:
694 self.constructor.add_constructor(tag, cls.from_yaml)
695 except AttributeError:
696
697 def f_y(constructor, node):
698 # type: (Any, Any) -> Any
699 return constructor.construct_yaml_object(node, cls)
700
701 self.constructor.add_constructor(tag, f_y)
702 return cls
703
704 def parse(self, stream):
705 # type: (StreamTextType) -> Any
706 """
707 Parse a YAML stream and produce parsing events.
708 """
709 _, parser = self.get_constructor_parser(stream)
710 try:
711 while parser.check_event():
712 yield parser.get_event()
713 finally:
714 parser.dispose()
715 try:
716 self._reader.reset_reader()
717 except AttributeError:
718 pass
719 try:
720 self._scanner.reset_scanner()
721 except AttributeError:
722 pass
723
724 # ### context manager
725
726 def __enter__(self):
727 # type: () -> Any
728 self._context_manager = YAMLContextManager(self)
729 return self
730
731 def __exit__(self, typ, value, traceback):
732 # type: (Any, Any, Any) -> None
733 if typ:
734 nprint("typ", typ)
735 self._context_manager.teardown_output()
736 # self._context_manager.teardown_input()
737 self._context_manager = None
738
739 # ### backwards compatibility
740 def _indent(self, mapping=None, sequence=None, offset=None):
741 # type: (Any, Any, Any) -> None
742 if mapping is not None:
743 self.map_indent = mapping
744 if sequence is not None:
745 self.sequence_indent = sequence
746 if offset is not None:
747 self.sequence_dash_offset = offset
748
749 @property
750 def indent(self):
751 # type: () -> Any
752 return self._indent
753
754 @indent.setter
755 def indent(self, val):
756 # type: (Any) -> None
757 self.old_indent = val
758
759 @property
760 def block_seq_indent(self):
761 # type: () -> Any
762 return self.sequence_dash_offset
763
764 @block_seq_indent.setter
765 def block_seq_indent(self, val):
766 # type: (Any) -> None
767 self.sequence_dash_offset = val
768
769 def compact(self, seq_seq=None, seq_map=None):
770 # type: (Any, Any) -> None
771 self.compact_seq_seq = seq_seq
772 self.compact_seq_map = seq_map
773
774
775 class YAMLContextManager(object):
776 def __init__(self, yaml, transform=None):
777 # type: (Any, Any) -> None # used to be: (Any, Optional[Callable]) -> None
778 self._yaml = yaml
779 self._output_inited = False
780 self._output_path = None
781 self._output = self._yaml._output
782 self._transform = transform
783
784 # self._input_inited = False
785 # self._input = input
786 # self._input_path = None
787 # self._transform = yaml.transform
788 # self._fstream = None
789
790 if not hasattr(self._output, "write") and hasattr(self._output, "open"):
791 # pathlib.Path() instance, open with the same mode
792 self._output_path = self._output
793 self._output = self._output_path.open("w")
794
795 # if not hasattr(self._stream, 'write') and hasattr(stream, 'open'):
796 # if not hasattr(self._input, 'read') and hasattr(self._input, 'open'):
797 # # pathlib.Path() instance, open with the same mode
798 # self._input_path = self._input
799 # self._input = self._input_path.open('r')
800
801 if self._transform is not None:
802 self._fstream = self._output
803 if self._yaml.encoding is None:
804 self._output = StringIO()
805 else:
806 self._output = BytesIO()
807
808 def teardown_output(self):
809 # type: () -> None
810 if self._output_inited:
811 self._yaml.serializer.close()
812 else:
813 return
814 try:
815 self._yaml.emitter.dispose()
816 except AttributeError:
817 raise
818 # self.dumper.dispose() # cyaml
819 try:
820 delattr(self._yaml, "_serializer")
821 delattr(self._yaml, "_emitter")
822 except AttributeError:
823 raise
824 if self._transform:
825 val = self._output.getvalue()
826 if self._yaml.encoding:
827 val = val.decode(self._yaml.encoding)
828 if self._fstream is None:
829 self._transform(val)
830 else:
831 self._fstream.write(self._transform(val))
832 self._fstream.flush()
833 self._output = self._fstream # maybe not necessary
834 if self._output_path is not None:
835 self._output.close()
836
837 def init_output(self, first_data):
838 # type: (Any) -> None
839 if self._yaml.top_level_colon_align is True:
840 tlca = max([len(str(x)) for x in first_data]) # type: Any
841 else:
842 tlca = self._yaml.top_level_colon_align
843 self._yaml.get_serializer_representer_emitter(self._output, tlca)
844 self._yaml.serializer.open()
845 self._output_inited = True
846
847 def dump(self, data):
848 # type: (Any) -> None
849 if not self._output_inited:
850 self.init_output(data)
851 try:
852 self._yaml.representer.represent(data)
853 except AttributeError:
854 # nprint(dir(dumper._representer))
855 raise
856
857 # def teardown_input(self):
858 # pass
859 #
860 # def init_input(self):
861 # # set the constructor and parser on YAML() instance
862 # self._yaml.get_constructor_parser(stream)
863 #
864 # def load(self):
865 # if not self._input_inited:
866 # self.init_input()
867 # try:
868 # while self._yaml.constructor.check_data():
869 # yield self._yaml.constructor.get_data()
870 # finally:
871 # parser.dispose()
872 # try:
873 # self._reader.reset_reader() # type: ignore
874 # except AttributeError:
875 # pass
876 # try:
877 # self._scanner.reset_scanner() # type: ignore
878 # except AttributeError:
879 # pass
880
881
882 def yaml_object(yml):
883 # type: (Any) -> Any
884 """decorator for classes that needs to dump/load objects
885 The tag for such objects is taken from the class attribute yaml_tag (or the
886 class name in lowercase in case unavailable)
887 If methods to_yaml and/or from_yaml are available, these are called for dumping resp.
888 loading, default routines (dumping a mapping of the attributes) used otherwise.
889 """
890
891 def yo_deco(cls):
892 # type: (Any) -> Any
893 tag = getattr(cls, "yaml_tag", "!" + cls.__name__)
894 try:
895 yml.representer.add_representer(cls, cls.to_yaml)
896 except AttributeError:
897
898 def t_y(representer, data):
899 # type: (Any, Any) -> Any
900 return representer.represent_yaml_object(
901 tag, data, cls, flow_style=representer.default_flow_style
902 )
903
904 yml.representer.add_representer(cls, t_y)
905 try:
906 yml.constructor.add_constructor(tag, cls.from_yaml)
907 except AttributeError:
908
909 def f_y(constructor, node):
910 # type: (Any, Any) -> Any
911 return constructor.construct_yaml_object(node, cls)
912
913 yml.constructor.add_constructor(tag, f_y)
914 return cls
915
916 return yo_deco
917
918
919 ########################################################################################
920
921
922 def scan(stream, Loader=Loader):
923 # type: (StreamTextType, Any) -> Any
924 """
925 Scan a YAML stream and produce scanning tokens.
926 """
927 loader = Loader(stream)
928 try:
929 while loader.scanner.check_token():
930 yield loader.scanner.get_token()
931 finally:
932 loader._parser.dispose()
933
934
935 def parse(stream, Loader=Loader):
936 # type: (StreamTextType, Any) -> Any
937 """
938 Parse a YAML stream and produce parsing events.
939 """
940 loader = Loader(stream)
941 try:
942 while loader._parser.check_event():
943 yield loader._parser.get_event()
944 finally:
945 loader._parser.dispose()
946
947
948 def compose(stream, Loader=Loader):
949 # type: (StreamTextType, Any) -> Any
950 """
951 Parse the first YAML document in a stream
952 and produce the corresponding representation tree.
953 """
954 loader = Loader(stream)
955 try:
956 return loader.get_single_node()
957 finally:
958 loader.dispose()
959
960
961 def compose_all(stream, Loader=Loader):
962 # type: (StreamTextType, Any) -> Any
963 """
964 Parse all YAML documents in a stream
965 and produce corresponding representation trees.
966 """
967 loader = Loader(stream)
968 try:
969 while loader.check_node():
970 yield loader._composer.get_node()
971 finally:
972 loader._parser.dispose()
973
974
975 def load(stream, Loader=None, version=None, preserve_quotes=None):
976 # type: (StreamTextType, Any, Optional[VersionType], Any) -> Any
977 """
978 Parse the first YAML document in a stream
979 and produce the corresponding Python object.
980 """
981 if Loader is None:
982 warnings.warn(UnsafeLoaderWarning.text, UnsafeLoaderWarning, stacklevel=2)
983 Loader = UnsafeLoader
984 loader = Loader(stream, version, preserve_quotes=preserve_quotes)
985 try:
986 return loader._constructor.get_single_data()
987 finally:
988 loader._parser.dispose()
989 try:
990 loader._reader.reset_reader()
991 except AttributeError:
992 pass
993 try:
994 loader._scanner.reset_scanner()
995 except AttributeError:
996 pass
997
998
999 def load_all(stream, Loader=None, version=None, preserve_quotes=None):
1000 # type: (Optional[StreamTextType], Any, Optional[VersionType], Optional[bool]) -> Any # NOQA
1001 """
1002 Parse all YAML documents in a stream
1003 and produce corresponding Python objects.
1004 """
1005 if Loader is None:
1006 warnings.warn(UnsafeLoaderWarning.text, UnsafeLoaderWarning, stacklevel=2)
1007 Loader = UnsafeLoader
1008 loader = Loader(stream, version, preserve_quotes=preserve_quotes)
1009 try:
1010 while loader._constructor.check_data():
1011 yield loader._constructor.get_data()
1012 finally:
1013 loader._parser.dispose()
1014 try:
1015 loader._reader.reset_reader()
1016 except AttributeError:
1017 pass
1018 try:
1019 loader._scanner.reset_scanner()
1020 except AttributeError:
1021 pass
1022
1023
1024 def safe_load(stream, version=None):
1025 # type: (StreamTextType, Optional[VersionType]) -> Any
1026 """
1027 Parse the first YAML document in a stream
1028 and produce the corresponding Python object.
1029 Resolve only basic YAML tags.
1030 """
1031 return load(stream, SafeLoader, version)
1032
1033
1034 def safe_load_all(stream, version=None):
1035 # type: (StreamTextType, Optional[VersionType]) -> Any
1036 """
1037 Parse all YAML documents in a stream
1038 and produce corresponding Python objects.
1039 Resolve only basic YAML tags.
1040 """
1041 return load_all(stream, SafeLoader, version)
1042
1043
1044 def round_trip_load(stream, version=None, preserve_quotes=None):
1045 # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> Any
1046 """
1047 Parse the first YAML document in a stream
1048 and produce the corresponding Python object.
1049 Resolve only basic YAML tags.
1050 """
1051 return load(stream, RoundTripLoader, version, preserve_quotes=preserve_quotes)
1052
1053
1054 def round_trip_load_all(stream, version=None, preserve_quotes=None):
1055 # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> Any
1056 """
1057 Parse all YAML documents in a stream
1058 and produce corresponding Python objects.
1059 Resolve only basic YAML tags.
1060 """
1061 return load_all(stream, RoundTripLoader, version, preserve_quotes=preserve_quotes)
1062
1063
1064 def emit(
1065 events,
1066 stream=None,
1067 Dumper=Dumper,
1068 canonical=None,
1069 indent=None,
1070 width=None,
1071 allow_unicode=None,
1072 line_break=None,
1073 ):
1074 # type: (Any, Optional[StreamType], Any, Optional[bool], Union[int, None], Optional[int], Optional[bool], Any) -> Any # NOQA
1075 """
1076 Emit YAML parsing events into a stream.
1077 If stream is None, return the produced string instead.
1078 """
1079 getvalue = None
1080 if stream is None:
1081 stream = StringIO()
1082 getvalue = stream.getvalue
1083 dumper = Dumper(
1084 stream,
1085 canonical=canonical,
1086 indent=indent,
1087 width=width,
1088 allow_unicode=allow_unicode,
1089 line_break=line_break,
1090 )
1091 try:
1092 for event in events:
1093 dumper.emit(event)
1094 finally:
1095 try:
1096 dumper._emitter.dispose()
1097 except AttributeError:
1098 raise
1099 dumper.dispose() # cyaml
1100 if getvalue is not None:
1101 return getvalue()
1102
1103
1104 enc = None if PY3 else "utf-8"
1105
1106
1107 def serialize_all(
1108 nodes,
1109 stream=None,
1110 Dumper=Dumper,
1111 canonical=None,
1112 indent=None,
1113 width=None,
1114 allow_unicode=None,
1115 line_break=None,
1116 encoding=enc,
1117 explicit_start=None,
1118 explicit_end=None,
1119 version=None,
1120 tags=None,
1121 ):
1122 # type: (Any, Optional[StreamType], Any, Any, Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Optional[VersionType], Any) -> Any # NOQA
1123 """
1124 Serialize a sequence of representation trees into a YAML stream.
1125 If stream is None, return the produced string instead.
1126 """
1127 getvalue = None
1128 if stream is None:
1129 if encoding is None:
1130 stream = StringIO()
1131 else:
1132 stream = BytesIO()
1133 getvalue = stream.getvalue
1134 dumper = Dumper(
1135 stream,
1136 canonical=canonical,
1137 indent=indent,
1138 width=width,
1139 allow_unicode=allow_unicode,
1140 line_break=line_break,
1141 encoding=encoding,
1142 version=version,
1143 tags=tags,
1144 explicit_start=explicit_start,
1145 explicit_end=explicit_end,
1146 )
1147 try:
1148 dumper._serializer.open()
1149 for node in nodes:
1150 dumper.serialize(node)
1151 dumper._serializer.close()
1152 finally:
1153 try:
1154 dumper._emitter.dispose()
1155 except AttributeError:
1156 raise
1157 dumper.dispose() # cyaml
1158 if getvalue is not None:
1159 return getvalue()
1160
1161
1162 def serialize(node, stream=None, Dumper=Dumper, **kwds):
1163 # type: (Any, Optional[StreamType], Any, Any) -> Any
1164 """
1165 Serialize a representation tree into a YAML stream.
1166 If stream is None, return the produced string instead.
1167 """
1168 return serialize_all([node], stream, Dumper=Dumper, **kwds)
1169
1170
1171 def dump_all(
1172 documents,
1173 stream=None,
1174 Dumper=Dumper,
1175 default_style=None,
1176 default_flow_style=None,
1177 canonical=None,
1178 indent=None,
1179 width=None,
1180 allow_unicode=None,
1181 line_break=None,
1182 encoding=enc,
1183 explicit_start=None,
1184 explicit_end=None,
1185 version=None,
1186 tags=None,
1187 block_seq_indent=None,
1188 top_level_colon_align=None,
1189 prefix_colon=None,
1190 ):
1191 # type: (Any, Optional[StreamType], Any, Any, Any, Optional[bool], Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Any, Any, Any, Any, Any) -> Optional[str] # NOQA
1192 """
1193 Serialize a sequence of Python objects into a YAML stream.
1194 If stream is None, return the produced string instead.
1195 """
1196 getvalue = None
1197 if top_level_colon_align is True:
1198 top_level_colon_align = max([len(str(x)) for x in documents[0]])
1199 if stream is None:
1200 if encoding is None:
1201 stream = StringIO()
1202 else:
1203 stream = BytesIO()
1204 getvalue = stream.getvalue
1205 dumper = Dumper(
1206 stream,
1207 default_style=default_style,
1208 default_flow_style=default_flow_style,
1209 canonical=canonical,
1210 indent=indent,
1211 width=width,
1212 allow_unicode=allow_unicode,
1213 line_break=line_break,
1214 encoding=encoding,
1215 explicit_start=explicit_start,
1216 explicit_end=explicit_end,
1217 version=version,
1218 tags=tags,
1219 block_seq_indent=block_seq_indent,
1220 top_level_colon_align=top_level_colon_align,
1221 prefix_colon=prefix_colon,
1222 )
1223 try:
1224 dumper._serializer.open()
1225 for data in documents:
1226 try:
1227 dumper._representer.represent(data)
1228 except AttributeError:
1229 # nprint(dir(dumper._representer))
1230 raise
1231 dumper._serializer.close()
1232 finally:
1233 try:
1234 dumper._emitter.dispose()
1235 except AttributeError:
1236 raise
1237 dumper.dispose() # cyaml
1238 if getvalue is not None:
1239 return getvalue()
1240 return None
1241
1242
1243 def dump(
1244 data,
1245 stream=None,
1246 Dumper=Dumper,
1247 default_style=None,
1248 default_flow_style=None,
1249 canonical=None,
1250 indent=None,
1251 width=None,
1252 allow_unicode=None,
1253 line_break=None,
1254 encoding=enc,
1255 explicit_start=None,
1256 explicit_end=None,
1257 version=None,
1258 tags=None,
1259 block_seq_indent=None,
1260 ):
1261 # type: (Any, Optional[StreamType], Any, Any, Any, Optional[bool], Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Optional[VersionType], Any, Any) -> Optional[str] # NOQA
1262 """
1263 Serialize a Python object into a YAML stream.
1264 If stream is None, return the produced string instead.
1265
1266 default_style ∈ None, '', '"', "'", '|', '>'
1267
1268 """
1269 return dump_all(
1270 [data],
1271 stream,
1272 Dumper=Dumper,
1273 default_style=default_style,
1274 default_flow_style=default_flow_style,
1275 canonical=canonical,
1276 indent=indent,
1277 width=width,
1278 allow_unicode=allow_unicode,
1279 line_break=line_break,
1280 encoding=encoding,
1281 explicit_start=explicit_start,
1282 explicit_end=explicit_end,
1283 version=version,
1284 tags=tags,
1285 block_seq_indent=block_seq_indent,
1286 )
1287
1288
1289 def safe_dump_all(documents, stream=None, **kwds):
1290 # type: (Any, Optional[StreamType], Any) -> Optional[str]
1291 """
1292 Serialize a sequence of Python objects into a YAML stream.
1293 Produce only basic YAML tags.
1294 If stream is None, return the produced string instead.
1295 """
1296 return dump_all(documents, stream, Dumper=SafeDumper, **kwds)
1297
1298
1299 def safe_dump(data, stream=None, **kwds):
1300 # type: (Any, Optional[StreamType], Any) -> Optional[str]
1301 """
1302 Serialize a Python object into a YAML stream.
1303 Produce only basic YAML tags.
1304 If stream is None, return the produced string instead.
1305 """
1306 return dump_all([data], stream, Dumper=SafeDumper, **kwds)
1307
1308
1309 def round_trip_dump(
1310 data,
1311 stream=None,
1312 Dumper=RoundTripDumper,
1313 default_style=None,
1314 default_flow_style=None,
1315 canonical=None,
1316 indent=None,
1317 width=None,
1318 allow_unicode=None,
1319 line_break=None,
1320 encoding=enc,
1321 explicit_start=None,
1322 explicit_end=None,
1323 version=None,
1324 tags=None,
1325 block_seq_indent=None,
1326 top_level_colon_align=None,
1327 prefix_colon=None,
1328 ):
1329 # type: (Any, Optional[StreamType], Any, Any, Any, Optional[bool], Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Optional[VersionType], Any, Any, Any, Any) -> Optional[str] # NOQA
1330 allow_unicode = True if allow_unicode is None else allow_unicode
1331 return dump_all(
1332 [data],
1333 stream,
1334 Dumper=Dumper,
1335 default_style=default_style,
1336 default_flow_style=default_flow_style,
1337 canonical=canonical,
1338 indent=indent,
1339 width=width,
1340 allow_unicode=allow_unicode,
1341 line_break=line_break,
1342 encoding=encoding,
1343 explicit_start=explicit_start,
1344 explicit_end=explicit_end,
1345 version=version,
1346 tags=tags,
1347 block_seq_indent=block_seq_indent,
1348 top_level_colon_align=top_level_colon_align,
1349 prefix_colon=prefix_colon,
1350 )
1351
1352
1353 # Loader/Dumper are no longer composites, to get to the associated
1354 # Resolver()/Representer(), etc., you need to instantiate the class
1355
1356
1357 def add_implicit_resolver(
1358 tag, regexp, first=None, Loader=None, Dumper=None, resolver=Resolver
1359 ):
1360 # type: (Any, Any, Any, Any, Any, Any) -> None
1361 """
1362 Add an implicit scalar detector.
1363 If an implicit scalar value matches the given regexp,
1364 the corresponding tag is assigned to the scalar.
1365 first is a sequence of possible initial characters or None.
1366 """
1367 if Loader is None and Dumper is None:
1368 resolver.add_implicit_resolver(tag, regexp, first)
1369 return
1370 if Loader:
1371 if hasattr(Loader, "add_implicit_resolver"):
1372 Loader.add_implicit_resolver(tag, regexp, first)
1373 elif issubclass(
1374 Loader,
1375 (BaseLoader, SafeLoader, strictyaml.ruamel.loader.Loader, RoundTripLoader),
1376 ):
1377 Resolver.add_implicit_resolver(tag, regexp, first)
1378 else:
1379 raise NotImplementedError
1380 if Dumper:
1381 if hasattr(Dumper, "add_implicit_resolver"):
1382 Dumper.add_implicit_resolver(tag, regexp, first)
1383 elif issubclass(
1384 Dumper,
1385 (BaseDumper, SafeDumper, strictyaml.ruamel.dumper.Dumper, RoundTripDumper),
1386 ):
1387 Resolver.add_implicit_resolver(tag, regexp, first)
1388 else:
1389 raise NotImplementedError
1390
1391
1392 # this code currently not tested
1393 def add_path_resolver(
1394 tag, path, kind=None, Loader=None, Dumper=None, resolver=Resolver
1395 ):
1396 # type: (Any, Any, Any, Any, Any, Any) -> None
1397 """
1398 Add a path based resolver for the given tag.
1399 A path is a list of keys that forms a path
1400 to a node in the representation tree.
1401 Keys can be string values, integers, or None.
1402 """
1403 if Loader is None and Dumper is None:
1404 resolver.add_path_resolver(tag, path, kind)
1405 return
1406 if Loader:
1407 if hasattr(Loader, "add_path_resolver"):
1408 Loader.add_path_resolver(tag, path, kind)
1409 elif issubclass(
1410 Loader,
1411 (BaseLoader, SafeLoader, strictyaml.ruamel.loader.Loader, RoundTripLoader),
1412 ):
1413 Resolver.add_path_resolver(tag, path, kind)
1414 else:
1415 raise NotImplementedError
1416 if Dumper:
1417 if hasattr(Dumper, "add_path_resolver"):
1418 Dumper.add_path_resolver(tag, path, kind)
1419 elif issubclass(
1420 Dumper,
1421 (BaseDumper, SafeDumper, strictyaml.ruamel.dumper.Dumper, RoundTripDumper),
1422 ):
1423 Resolver.add_path_resolver(tag, path, kind)
1424 else:
1425 raise NotImplementedError
1426
1427
1428 def add_constructor(tag, object_constructor, Loader=None, constructor=Constructor):
1429 # type: (Any, Any, Any, Any) -> None
1430 """
1431 Add an object constructor for the given tag.
1432 object_onstructor is a function that accepts a Loader instance
1433 and a node object and produces the corresponding Python object.
1434 """
1435 if Loader is None:
1436 constructor.add_constructor(tag, object_constructor)
1437 else:
1438 if hasattr(Loader, "add_constructor"):
1439 Loader.add_constructor(tag, object_constructor)
1440 return
1441 if issubclass(Loader, BaseLoader):
1442 BaseConstructor.add_constructor(tag, object_constructor)
1443 elif issubclass(Loader, SafeLoader):
1444 SafeConstructor.add_constructor(tag, object_constructor)
1445 elif issubclass(Loader, Loader):
1446 Constructor.add_constructor(tag, object_constructor)
1447 elif issubclass(Loader, RoundTripLoader):
1448 RoundTripConstructor.add_constructor(tag, object_constructor)
1449 else:
1450 raise NotImplementedError
1451
1452
1453 def add_multi_constructor(
1454 tag_prefix, multi_constructor, Loader=None, constructor=Constructor
1455 ):
1456 # type: (Any, Any, Any, Any) -> None
1457 """
1458 Add a multi-constructor for the given tag prefix.
1459 Multi-constructor is called for a node if its tag starts with tag_prefix.
1460 Multi-constructor accepts a Loader instance, a tag suffix,
1461 and a node object and produces the corresponding Python object.
1462 """
1463 if Loader is None:
1464 constructor.add_multi_constructor(tag_prefix, multi_constructor)
1465 else:
1466 if False and hasattr(Loader, "add_multi_constructor"):
1467 Loader.add_multi_constructor(tag_prefix, constructor)
1468 return
1469 if issubclass(Loader, BaseLoader):
1470 BaseConstructor.add_multi_constructor(tag_prefix, multi_constructor)
1471 elif issubclass(Loader, SafeLoader):
1472 SafeConstructor.add_multi_constructor(tag_prefix, multi_constructor)
1473 elif issubclass(Loader, strictyaml.ruamel.loader.Loader):
1474 Constructor.add_multi_constructor(tag_prefix, multi_constructor)
1475 elif issubclass(Loader, RoundTripLoader):
1476 RoundTripConstructor.add_multi_constructor(tag_prefix, multi_constructor)
1477 else:
1478 raise NotImplementedError
1479
1480
1481 def add_representer(
1482 data_type, object_representer, Dumper=None, representer=Representer
1483 ):
1484 # type: (Any, Any, Any, Any) -> None
1485 """
1486 Add a representer for the given type.
1487 object_representer is a function accepting a Dumper instance
1488 and an instance of the given data type
1489 and producing the corresponding representation node.
1490 """
1491 if Dumper is None:
1492 representer.add_representer(data_type, object_representer)
1493 else:
1494 if hasattr(Dumper, "add_representer"):
1495 Dumper.add_representer(data_type, object_representer)
1496 return
1497 if issubclass(Dumper, BaseDumper):
1498 BaseRepresenter.add_representer(data_type, object_representer)
1499 elif issubclass(Dumper, SafeDumper):
1500 SafeRepresenter.add_representer(data_type, object_representer)
1501 elif issubclass(Dumper, Dumper):
1502 Representer.add_representer(data_type, object_representer)
1503 elif issubclass(Dumper, RoundTripDumper):
1504 RoundTripRepresenter.add_representer(data_type, object_representer)
1505 else:
1506 raise NotImplementedError
1507
1508
1509 # this code currently not tested
1510 def add_multi_representer(
1511 data_type, multi_representer, Dumper=None, representer=Representer
1512 ):
1513 # type: (Any, Any, Any, Any) -> None
1514 """
1515 Add a representer for the given type.
1516 multi_representer is a function accepting a Dumper instance
1517 and an instance of the given data type or subtype
1518 and producing the corresponding representation node.
1519 """
1520 if Dumper is None:
1521 representer.add_multi_representer(data_type, multi_representer)
1522 else:
1523 if hasattr(Dumper, "add_multi_representer"):
1524 Dumper.add_multi_representer(data_type, multi_representer)
1525 return
1526 if issubclass(Dumper, BaseDumper):
1527 BaseRepresenter.add_multi_representer(data_type, multi_representer)
1528 elif issubclass(Dumper, SafeDumper):
1529 SafeRepresenter.add_multi_representer(data_type, multi_representer)
1530 elif issubclass(Dumper, Dumper):
1531 Representer.add_multi_representer(data_type, multi_representer)
1532 elif issubclass(Dumper, RoundTripDumper):
1533 RoundTripRepresenter.add_multi_representer(data_type, multi_representer)
1534 else:
1535 raise NotImplementedError
1536
1537
1538 class YAMLObjectMetaclass(type):
1539 """
1540 The metaclass for YAMLObject.
1541 """
1542
1543 def __init__(cls, name, bases, kwds):
1544 # type: (Any, Any, Any) -> None
1545 super(YAMLObjectMetaclass, cls).__init__(name, bases, kwds)
1546 if "yaml_tag" in kwds and kwds["yaml_tag"] is not None:
1547 cls.yaml_constructor.add_constructor(cls.yaml_tag, cls.from_yaml) # type: ignore
1548 cls.yaml_representer.add_representer(cls, cls.to_yaml) # type: ignore
1549
1550
1551 class YAMLObject(with_metaclass(YAMLObjectMetaclass)): # type: ignore
1552 """
1553 An object that can dump itself to a YAML stream
1554 and load itself from a YAML stream.
1555 """
1556
1557 __slots__ = () # no direct instantiation, so allow immutable subclasses
1558
1559 yaml_constructor = Constructor
1560 yaml_representer = Representer
1561
1562 yaml_tag = None # type: Any
1563 yaml_flow_style = None # type: Any
1564
1565 @classmethod
1566 def from_yaml(cls, constructor, node):
1567 # type: (Any, Any) -> Any
1568 """
1569 Convert a representation node to a Python object.
1570 """
1571 return constructor.construct_yaml_object(node, cls)
1572
1573 @classmethod
1574 def to_yaml(cls, representer, data):
1575 # type: (Any, Any) -> Any
1576 """
1577 Convert a Python object to a representation node.
1578 """
1579 return representer.represent_yaml_object(
1580 cls.yaml_tag, data, cls, flow_style=cls.yaml_flow_style
1581 )