__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. from .error import *
  2. from .tokens import *
  3. from .events import *
  4. from .nodes import *
  5. from .loader import *
  6. from .dumper import *
  7. __version__ = '5.4.1'
  8. try:
  9. from .cyaml import *
  10. __with_libyaml__ = True
  11. except ImportError:
  12. __with_libyaml__ = False
  13. import io
  14. #------------------------------------------------------------------------------
  15. # Warnings control
  16. #------------------------------------------------------------------------------
  17. # 'Global' warnings state:
  18. _warnings_enabled = {
  19. 'YAMLLoadWarning': True,
  20. }
  21. # Get or set global warnings' state
  22. def warnings(settings=None):
  23. if settings is None:
  24. return _warnings_enabled
  25. if type(settings) is dict:
  26. for key in settings:
  27. if key in _warnings_enabled:
  28. _warnings_enabled[key] = settings[key]
  29. # Warn when load() is called without Loader=...
  30. class YAMLLoadWarning(RuntimeWarning):
  31. pass
  32. def load_warning(method):
  33. if _warnings_enabled['YAMLLoadWarning'] is False:
  34. return
  35. import warnings
  36. message = (
  37. "calling yaml.%s() without Loader=... is deprecated, as the "
  38. "default Loader is unsafe. Please read "
  39. "https://msg.pyyaml.org/load for full details."
  40. ) % method
  41. warnings.warn(message, YAMLLoadWarning, stacklevel=3)
  42. #------------------------------------------------------------------------------
  43. def scan(stream, Loader=Loader):
  44. """
  45. Scan a YAML stream and produce scanning tokens.
  46. """
  47. loader = Loader(stream)
  48. try:
  49. while loader.check_token():
  50. yield loader.get_token()
  51. finally:
  52. loader.dispose()
  53. def parse(stream, Loader=Loader):
  54. """
  55. Parse a YAML stream and produce parsing events.
  56. """
  57. loader = Loader(stream)
  58. try:
  59. while loader.check_event():
  60. yield loader.get_event()
  61. finally:
  62. loader.dispose()
  63. def compose(stream, Loader=Loader):
  64. """
  65. Parse the first YAML document in a stream
  66. and produce the corresponding representation tree.
  67. """
  68. loader = Loader(stream)
  69. try:
  70. return loader.get_single_node()
  71. finally:
  72. loader.dispose()
  73. def compose_all(stream, Loader=Loader):
  74. """
  75. Parse all YAML documents in a stream
  76. and produce corresponding representation trees.
  77. """
  78. loader = Loader(stream)
  79. try:
  80. while loader.check_node():
  81. yield loader.get_node()
  82. finally:
  83. loader.dispose()
  84. def load(stream, Loader=None):
  85. """
  86. Parse the first YAML document in a stream
  87. and produce the corresponding Python object.
  88. """
  89. if Loader is None:
  90. load_warning('load')
  91. Loader = FullLoader
  92. loader = Loader(stream)
  93. try:
  94. return loader.get_single_data()
  95. finally:
  96. loader.dispose()
  97. def load_all(stream, Loader=None):
  98. """
  99. Parse all YAML documents in a stream
  100. and produce corresponding Python objects.
  101. """
  102. if Loader is None:
  103. load_warning('load_all')
  104. Loader = FullLoader
  105. loader = Loader(stream)
  106. try:
  107. while loader.check_data():
  108. yield loader.get_data()
  109. finally:
  110. loader.dispose()
  111. def full_load(stream):
  112. """
  113. Parse the first YAML document in a stream
  114. and produce the corresponding Python object.
  115. Resolve all tags except those known to be
  116. unsafe on untrusted input.
  117. """
  118. return load(stream, FullLoader)
  119. def full_load_all(stream):
  120. """
  121. Parse all YAML documents in a stream
  122. and produce corresponding Python objects.
  123. Resolve all tags except those known to be
  124. unsafe on untrusted input.
  125. """
  126. return load_all(stream, FullLoader)
  127. def safe_load(stream):
  128. """
  129. Parse the first YAML document in a stream
  130. and produce the corresponding Python object.
  131. Resolve only basic YAML tags. This is known
  132. to be safe for untrusted input.
  133. """
  134. return load(stream, SafeLoader)
  135. def safe_load_all(stream):
  136. """
  137. Parse all YAML documents in a stream
  138. and produce corresponding Python objects.
  139. Resolve only basic YAML tags. This is known
  140. to be safe for untrusted input.
  141. """
  142. return load_all(stream, SafeLoader)
  143. def unsafe_load(stream):
  144. """
  145. Parse the first YAML document in a stream
  146. and produce the corresponding Python object.
  147. Resolve all tags, even those known to be
  148. unsafe on untrusted input.
  149. """
  150. return load(stream, UnsafeLoader)
  151. def unsafe_load_all(stream):
  152. """
  153. Parse all YAML documents in a stream
  154. and produce corresponding Python objects.
  155. Resolve all tags, even those known to be
  156. unsafe on untrusted input.
  157. """
  158. return load_all(stream, UnsafeLoader)
  159. def emit(events, stream=None, Dumper=Dumper,
  160. canonical=None, indent=None, width=None,
  161. allow_unicode=None, line_break=None):
  162. """
  163. Emit YAML parsing events into a stream.
  164. If stream is None, return the produced string instead.
  165. """
  166. getvalue = None
  167. if stream is None:
  168. stream = io.StringIO()
  169. getvalue = stream.getvalue
  170. dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
  171. allow_unicode=allow_unicode, line_break=line_break)
  172. try:
  173. for event in events:
  174. dumper.emit(event)
  175. finally:
  176. dumper.dispose()
  177. if getvalue:
  178. return getvalue()
  179. def serialize_all(nodes, stream=None, Dumper=Dumper,
  180. canonical=None, indent=None, width=None,
  181. allow_unicode=None, line_break=None,
  182. encoding=None, explicit_start=None, explicit_end=None,
  183. version=None, tags=None):
  184. """
  185. Serialize a sequence of representation trees into a YAML stream.
  186. If stream is None, return the produced string instead.
  187. """
  188. getvalue = None
  189. if stream is None:
  190. if encoding is None:
  191. stream = io.StringIO()
  192. else:
  193. stream = io.BytesIO()
  194. getvalue = stream.getvalue
  195. dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
  196. allow_unicode=allow_unicode, line_break=line_break,
  197. encoding=encoding, version=version, tags=tags,
  198. explicit_start=explicit_start, explicit_end=explicit_end)
  199. try:
  200. dumper.open()
  201. for node in nodes:
  202. dumper.serialize(node)
  203. dumper.close()
  204. finally:
  205. dumper.dispose()
  206. if getvalue:
  207. return getvalue()
  208. def serialize(node, stream=None, Dumper=Dumper, **kwds):
  209. """
  210. Serialize a representation tree into a YAML stream.
  211. If stream is None, return the produced string instead.
  212. """
  213. return serialize_all([node], stream, Dumper=Dumper, **kwds)
  214. def dump_all(documents, stream=None, Dumper=Dumper,
  215. default_style=None, default_flow_style=False,
  216. canonical=None, indent=None, width=None,
  217. allow_unicode=None, line_break=None,
  218. encoding=None, explicit_start=None, explicit_end=None,
  219. version=None, tags=None, sort_keys=True):
  220. """
  221. Serialize a sequence of Python objects into a YAML stream.
  222. If stream is None, return the produced string instead.
  223. """
  224. getvalue = None
  225. if stream is None:
  226. if encoding is None:
  227. stream = io.StringIO()
  228. else:
  229. stream = io.BytesIO()
  230. getvalue = stream.getvalue
  231. dumper = Dumper(stream, default_style=default_style,
  232. default_flow_style=default_flow_style,
  233. canonical=canonical, indent=indent, width=width,
  234. allow_unicode=allow_unicode, line_break=line_break,
  235. encoding=encoding, version=version, tags=tags,
  236. explicit_start=explicit_start, explicit_end=explicit_end, sort_keys=sort_keys)
  237. try:
  238. dumper.open()
  239. for data in documents:
  240. dumper.represent(data)
  241. dumper.close()
  242. finally:
  243. dumper.dispose()
  244. if getvalue:
  245. return getvalue()
  246. def dump(data, stream=None, Dumper=Dumper, **kwds):
  247. """
  248. Serialize a Python object into a YAML stream.
  249. If stream is None, return the produced string instead.
  250. """
  251. return dump_all([data], stream, Dumper=Dumper, **kwds)
  252. def safe_dump_all(documents, stream=None, **kwds):
  253. """
  254. Serialize a sequence of Python objects into a YAML stream.
  255. Produce only basic YAML tags.
  256. If stream is None, return the produced string instead.
  257. """
  258. return dump_all(documents, stream, Dumper=SafeDumper, **kwds)
  259. def safe_dump(data, stream=None, **kwds):
  260. """
  261. Serialize a Python object into a YAML stream.
  262. Produce only basic YAML tags.
  263. If stream is None, return the produced string instead.
  264. """
  265. return dump_all([data], stream, Dumper=SafeDumper, **kwds)
  266. def add_implicit_resolver(tag, regexp, first=None,
  267. Loader=None, Dumper=Dumper):
  268. """
  269. Add an implicit scalar detector.
  270. If an implicit scalar value matches the given regexp,
  271. the corresponding tag is assigned to the scalar.
  272. first is a sequence of possible initial characters or None.
  273. """
  274. if Loader is None:
  275. loader.Loader.add_implicit_resolver(tag, regexp, first)
  276. loader.FullLoader.add_implicit_resolver(tag, regexp, first)
  277. loader.UnsafeLoader.add_implicit_resolver(tag, regexp, first)
  278. else:
  279. Loader.add_implicit_resolver(tag, regexp, first)
  280. Dumper.add_implicit_resolver(tag, regexp, first)
  281. def add_path_resolver(tag, path, kind=None, Loader=None, Dumper=Dumper):
  282. """
  283. Add a path based resolver for the given tag.
  284. A path is a list of keys that forms a path
  285. to a node in the representation tree.
  286. Keys can be string values, integers, or None.
  287. """
  288. if Loader is None:
  289. loader.Loader.add_path_resolver(tag, path, kind)
  290. loader.FullLoader.add_path_resolver(tag, path, kind)
  291. loader.UnsafeLoader.add_path_resolver(tag, path, kind)
  292. else:
  293. Loader.add_path_resolver(tag, path, kind)
  294. Dumper.add_path_resolver(tag, path, kind)
  295. def add_constructor(tag, constructor, Loader=None):
  296. """
  297. Add a constructor for the given tag.
  298. Constructor is a function that accepts a Loader instance
  299. and a node object and produces the corresponding Python object.
  300. """
  301. if Loader is None:
  302. loader.Loader.add_constructor(tag, constructor)
  303. loader.FullLoader.add_constructor(tag, constructor)
  304. loader.UnsafeLoader.add_constructor(tag, constructor)
  305. else:
  306. Loader.add_constructor(tag, constructor)
  307. def add_multi_constructor(tag_prefix, multi_constructor, Loader=None):
  308. """
  309. Add a multi-constructor for the given tag prefix.
  310. Multi-constructor is called for a node if its tag starts with tag_prefix.
  311. Multi-constructor accepts a Loader instance, a tag suffix,
  312. and a node object and produces the corresponding Python object.
  313. """
  314. if Loader is None:
  315. loader.Loader.add_multi_constructor(tag_prefix, multi_constructor)
  316. loader.FullLoader.add_multi_constructor(tag_prefix, multi_constructor)
  317. loader.UnsafeLoader.add_multi_constructor(tag_prefix, multi_constructor)
  318. else:
  319. Loader.add_multi_constructor(tag_prefix, multi_constructor)
  320. def add_representer(data_type, representer, Dumper=Dumper):
  321. """
  322. Add a representer for the given type.
  323. Representer is a function accepting a Dumper instance
  324. and an instance of the given data type
  325. and producing the corresponding representation node.
  326. """
  327. Dumper.add_representer(data_type, representer)
  328. def add_multi_representer(data_type, multi_representer, Dumper=Dumper):
  329. """
  330. Add a representer for the given type.
  331. Multi-representer is a function accepting a Dumper instance
  332. and an instance of the given data type or subtype
  333. and producing the corresponding representation node.
  334. """
  335. Dumper.add_multi_representer(data_type, multi_representer)
  336. class YAMLObjectMetaclass(type):
  337. """
  338. The metaclass for YAMLObject.
  339. """
  340. def __init__(cls, name, bases, kwds):
  341. super(YAMLObjectMetaclass, cls).__init__(name, bases, kwds)
  342. if 'yaml_tag' in kwds and kwds['yaml_tag'] is not None:
  343. if isinstance(cls.yaml_loader, list):
  344. for loader in cls.yaml_loader:
  345. loader.add_constructor(cls.yaml_tag, cls.from_yaml)
  346. else:
  347. cls.yaml_loader.add_constructor(cls.yaml_tag, cls.from_yaml)
  348. cls.yaml_dumper.add_representer(cls, cls.to_yaml)
  349. class YAMLObject(metaclass=YAMLObjectMetaclass):
  350. """
  351. An object that can dump itself to a YAML stream
  352. and load itself from a YAML stream.
  353. """
  354. __slots__ = () # no direct instantiation, so allow immutable subclasses
  355. yaml_loader = [Loader, FullLoader, UnsafeLoader]
  356. yaml_dumper = Dumper
  357. yaml_tag = None
  358. yaml_flow_style = None
  359. @classmethod
  360. def from_yaml(cls, loader, node):
  361. """
  362. Convert a representation node to a Python object.
  363. """
  364. return loader.construct_yaml_object(node, cls)
  365. @classmethod
  366. def to_yaml(cls, dumper, data):
  367. """
  368. Convert a Python object to a representation node.
  369. """
  370. return dumper.represent_yaml_object(cls.yaml_tag, data, cls,
  371. flow_style=cls.yaml_flow_style)