您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

721 行
26 KiB

  1. __all__ = [
  2. 'BaseConstructor',
  3. 'SafeConstructor',
  4. 'FullConstructor',
  5. 'UnsafeConstructor',
  6. 'Constructor',
  7. 'ConstructorError'
  8. ]
  9. from .error import *
  10. from .nodes import *
  11. import collections.abc, datetime, base64, binascii, re, sys, types
  12. class ConstructorError(MarkedYAMLError):
  13. pass
  14. class BaseConstructor:
  15. yaml_constructors = {}
  16. yaml_multi_constructors = {}
  17. def __init__(self):
  18. self.constructed_objects = {}
  19. self.recursive_objects = {}
  20. self.state_generators = []
  21. self.deep_construct = False
  22. def check_data(self):
  23. # If there are more documents available?
  24. return self.check_node()
  25. def get_data(self):
  26. # Construct and return the next document.
  27. if self.check_node():
  28. return self.construct_document(self.get_node())
  29. def get_single_data(self):
  30. # Ensure that the stream contains a single document and construct it.
  31. node = self.get_single_node()
  32. if node is not None:
  33. return self.construct_document(node)
  34. return None
  35. def construct_document(self, node):
  36. data = self.construct_object(node)
  37. while self.state_generators:
  38. state_generators = self.state_generators
  39. self.state_generators = []
  40. for generator in state_generators:
  41. for dummy in generator:
  42. pass
  43. self.constructed_objects = {}
  44. self.recursive_objects = {}
  45. self.deep_construct = False
  46. return data
  47. def construct_object(self, node, deep=False):
  48. if node in self.constructed_objects:
  49. return self.constructed_objects[node]
  50. if deep:
  51. old_deep = self.deep_construct
  52. self.deep_construct = True
  53. if node in self.recursive_objects:
  54. raise ConstructorError(None, None,
  55. "found unconstructable recursive node", node.start_mark)
  56. self.recursive_objects[node] = None
  57. constructor = None
  58. tag_suffix = None
  59. if node.tag in self.yaml_constructors:
  60. constructor = self.yaml_constructors[node.tag]
  61. else:
  62. for tag_prefix in self.yaml_multi_constructors:
  63. if node.tag.startswith(tag_prefix):
  64. tag_suffix = node.tag[len(tag_prefix):]
  65. constructor = self.yaml_multi_constructors[tag_prefix]
  66. break
  67. else:
  68. if None in self.yaml_multi_constructors:
  69. tag_suffix = node.tag
  70. constructor = self.yaml_multi_constructors[None]
  71. elif None in self.yaml_constructors:
  72. constructor = self.yaml_constructors[None]
  73. elif isinstance(node, ScalarNode):
  74. constructor = self.__class__.construct_scalar
  75. elif isinstance(node, SequenceNode):
  76. constructor = self.__class__.construct_sequence
  77. elif isinstance(node, MappingNode):
  78. constructor = self.__class__.construct_mapping
  79. if tag_suffix is None:
  80. data = constructor(self, node)
  81. else:
  82. data = constructor(self, tag_suffix, node)
  83. if isinstance(data, types.GeneratorType):
  84. generator = data
  85. data = next(generator)
  86. if self.deep_construct:
  87. for dummy in generator:
  88. pass
  89. else:
  90. self.state_generators.append(generator)
  91. self.constructed_objects[node] = data
  92. del self.recursive_objects[node]
  93. if deep:
  94. self.deep_construct = old_deep
  95. return data
  96. def construct_scalar(self, node):
  97. if not isinstance(node, ScalarNode):
  98. raise ConstructorError(None, None,
  99. "expected a scalar node, but found %s" % node.id,
  100. node.start_mark)
  101. return node.value
  102. def construct_sequence(self, node, deep=False):
  103. if not isinstance(node, SequenceNode):
  104. raise ConstructorError(None, None,
  105. "expected a sequence node, but found %s" % node.id,
  106. node.start_mark)
  107. return [self.construct_object(child, deep=deep)
  108. for child in node.value]
  109. def construct_mapping(self, node, deep=False):
  110. if not isinstance(node, MappingNode):
  111. raise ConstructorError(None, None,
  112. "expected a mapping node, but found %s" % node.id,
  113. node.start_mark)
  114. mapping = {}
  115. for key_node, value_node in node.value:
  116. key = self.construct_object(key_node, deep=deep)
  117. if not isinstance(key, collections.abc.Hashable):
  118. raise ConstructorError("while constructing a mapping", node.start_mark,
  119. "found unhashable key", key_node.start_mark)
  120. value = self.construct_object(value_node, deep=deep)
  121. mapping[key] = value
  122. return mapping
  123. def construct_pairs(self, node, deep=False):
  124. if not isinstance(node, MappingNode):
  125. raise ConstructorError(None, None,
  126. "expected a mapping node, but found %s" % node.id,
  127. node.start_mark)
  128. pairs = []
  129. for key_node, value_node in node.value:
  130. key = self.construct_object(key_node, deep=deep)
  131. value = self.construct_object(value_node, deep=deep)
  132. pairs.append((key, value))
  133. return pairs
  134. @classmethod
  135. def add_constructor(cls, tag, constructor):
  136. if not 'yaml_constructors' in cls.__dict__:
  137. cls.yaml_constructors = cls.yaml_constructors.copy()
  138. cls.yaml_constructors[tag] = constructor
  139. @classmethod
  140. def add_multi_constructor(cls, tag_prefix, multi_constructor):
  141. if not 'yaml_multi_constructors' in cls.__dict__:
  142. cls.yaml_multi_constructors = cls.yaml_multi_constructors.copy()
  143. cls.yaml_multi_constructors[tag_prefix] = multi_constructor
  144. class SafeConstructor(BaseConstructor):
  145. def construct_scalar(self, node):
  146. if isinstance(node, MappingNode):
  147. for key_node, value_node in node.value:
  148. if key_node.tag == 'tag:yaml.org,2002:value':
  149. return self.construct_scalar(value_node)
  150. return super().construct_scalar(node)
  151. def flatten_mapping(self, node):
  152. merge = []
  153. index = 0
  154. while index < len(node.value):
  155. key_node, value_node = node.value[index]
  156. if key_node.tag == 'tag:yaml.org,2002:merge':
  157. del node.value[index]
  158. if isinstance(value_node, MappingNode):
  159. self.flatten_mapping(value_node)
  160. merge.extend(value_node.value)
  161. elif isinstance(value_node, SequenceNode):
  162. submerge = []
  163. for subnode in value_node.value:
  164. if not isinstance(subnode, MappingNode):
  165. raise ConstructorError("while constructing a mapping",
  166. node.start_mark,
  167. "expected a mapping for merging, but found %s"
  168. % subnode.id, subnode.start_mark)
  169. self.flatten_mapping(subnode)
  170. submerge.append(subnode.value)
  171. submerge.reverse()
  172. for value in submerge:
  173. merge.extend(value)
  174. else:
  175. raise ConstructorError("while constructing a mapping", node.start_mark,
  176. "expected a mapping or list of mappings for merging, but found %s"
  177. % value_node.id, value_node.start_mark)
  178. elif key_node.tag == 'tag:yaml.org,2002:value':
  179. key_node.tag = 'tag:yaml.org,2002:str'
  180. index += 1
  181. else:
  182. index += 1
  183. if merge:
  184. node.value = merge + node.value
  185. def construct_mapping(self, node, deep=False):
  186. if isinstance(node, MappingNode):
  187. self.flatten_mapping(node)
  188. return super().construct_mapping(node, deep=deep)
  189. def construct_yaml_null(self, node):
  190. self.construct_scalar(node)
  191. return None
  192. bool_values = {
  193. 'yes': True,
  194. 'no': False,
  195. 'true': True,
  196. 'false': False,
  197. 'on': True,
  198. 'off': False,
  199. }
  200. def construct_yaml_bool(self, node):
  201. value = self.construct_scalar(node)
  202. return self.bool_values[value.lower()]
  203. def construct_yaml_int(self, node):
  204. value = self.construct_scalar(node)
  205. value = value.replace('_', '')
  206. sign = +1
  207. if value[0] == '-':
  208. sign = -1
  209. if value[0] in '+-':
  210. value = value[1:]
  211. if value == '0':
  212. return 0
  213. elif value.startswith('0b'):
  214. return sign*int(value[2:], 2)
  215. elif value.startswith('0x'):
  216. return sign*int(value[2:], 16)
  217. elif value[0] == '0':
  218. return sign*int(value, 8)
  219. elif ':' in value:
  220. digits = [int(part) for part in value.split(':')]
  221. digits.reverse()
  222. base = 1
  223. value = 0
  224. for digit in digits:
  225. value += digit*base
  226. base *= 60
  227. return sign*value
  228. else:
  229. return sign*int(value)
  230. inf_value = 1e300
  231. while inf_value != inf_value*inf_value:
  232. inf_value *= inf_value
  233. nan_value = -inf_value/inf_value # Trying to make a quiet NaN (like C99).
  234. def construct_yaml_float(self, node):
  235. value = self.construct_scalar(node)
  236. value = value.replace('_', '').lower()
  237. sign = +1
  238. if value[0] == '-':
  239. sign = -1
  240. if value[0] in '+-':
  241. value = value[1:]
  242. if value == '.inf':
  243. return sign*self.inf_value
  244. elif value == '.nan':
  245. return self.nan_value
  246. elif ':' in value:
  247. digits = [float(part) for part in value.split(':')]
  248. digits.reverse()
  249. base = 1
  250. value = 0.0
  251. for digit in digits:
  252. value += digit*base
  253. base *= 60
  254. return sign*value
  255. else:
  256. return sign*float(value)
  257. def construct_yaml_binary(self, node):
  258. try:
  259. value = self.construct_scalar(node).encode('ascii')
  260. except UnicodeEncodeError as exc:
  261. raise ConstructorError(None, None,
  262. "failed to convert base64 data into ascii: %s" % exc,
  263. node.start_mark)
  264. try:
  265. if hasattr(base64, 'decodebytes'):
  266. return base64.decodebytes(value)
  267. else:
  268. return base64.decodestring(value)
  269. except binascii.Error as exc:
  270. raise ConstructorError(None, None,
  271. "failed to decode base64 data: %s" % exc, node.start_mark)
  272. timestamp_regexp = re.compile(
  273. r'''^(?P<year>[0-9][0-9][0-9][0-9])
  274. -(?P<month>[0-9][0-9]?)
  275. -(?P<day>[0-9][0-9]?)
  276. (?:(?:[Tt]|[ \t]+)
  277. (?P<hour>[0-9][0-9]?)
  278. :(?P<minute>[0-9][0-9])
  279. :(?P<second>[0-9][0-9])
  280. (?:\.(?P<fraction>[0-9]*))?
  281. (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
  282. (?::(?P<tz_minute>[0-9][0-9]))?))?)?$''', re.X)
  283. def construct_yaml_timestamp(self, node):
  284. value = self.construct_scalar(node)
  285. match = self.timestamp_regexp.match(node.value)
  286. values = match.groupdict()
  287. year = int(values['year'])
  288. month = int(values['month'])
  289. day = int(values['day'])
  290. if not values['hour']:
  291. return datetime.date(year, month, day)
  292. hour = int(values['hour'])
  293. minute = int(values['minute'])
  294. second = int(values['second'])
  295. fraction = 0
  296. if values['fraction']:
  297. fraction = values['fraction'][:6]
  298. while len(fraction) < 6:
  299. fraction += '0'
  300. fraction = int(fraction)
  301. delta = None
  302. if values['tz_sign']:
  303. tz_hour = int(values['tz_hour'])
  304. tz_minute = int(values['tz_minute'] or 0)
  305. delta = datetime.timedelta(hours=tz_hour, minutes=tz_minute)
  306. if values['tz_sign'] == '-':
  307. delta = -delta
  308. data = datetime.datetime(year, month, day, hour, minute, second, fraction)
  309. if delta:
  310. data -= delta
  311. return data
  312. def construct_yaml_omap(self, node):
  313. # Note: we do not check for duplicate keys, because it's too
  314. # CPU-expensive.
  315. omap = []
  316. yield omap
  317. if not isinstance(node, SequenceNode):
  318. raise ConstructorError("while constructing an ordered map", node.start_mark,
  319. "expected a sequence, but found %s" % node.id, node.start_mark)
  320. for subnode in node.value:
  321. if not isinstance(subnode, MappingNode):
  322. raise ConstructorError("while constructing an ordered map", node.start_mark,
  323. "expected a mapping of length 1, but found %s" % subnode.id,
  324. subnode.start_mark)
  325. if len(subnode.value) != 1:
  326. raise ConstructorError("while constructing an ordered map", node.start_mark,
  327. "expected a single mapping item, but found %d items" % len(subnode.value),
  328. subnode.start_mark)
  329. key_node, value_node = subnode.value[0]
  330. key = self.construct_object(key_node)
  331. value = self.construct_object(value_node)
  332. omap.append((key, value))
  333. def construct_yaml_pairs(self, node):
  334. # Note: the same code as `construct_yaml_omap`.
  335. pairs = []
  336. yield pairs
  337. if not isinstance(node, SequenceNode):
  338. raise ConstructorError("while constructing pairs", node.start_mark,
  339. "expected a sequence, but found %s" % node.id, node.start_mark)
  340. for subnode in node.value:
  341. if not isinstance(subnode, MappingNode):
  342. raise ConstructorError("while constructing pairs", node.start_mark,
  343. "expected a mapping of length 1, but found %s" % subnode.id,
  344. subnode.start_mark)
  345. if len(subnode.value) != 1:
  346. raise ConstructorError("while constructing pairs", node.start_mark,
  347. "expected a single mapping item, but found %d items" % len(subnode.value),
  348. subnode.start_mark)
  349. key_node, value_node = subnode.value[0]
  350. key = self.construct_object(key_node)
  351. value = self.construct_object(value_node)
  352. pairs.append((key, value))
  353. def construct_yaml_set(self, node):
  354. data = set()
  355. yield data
  356. value = self.construct_mapping(node)
  357. data.update(value)
  358. def construct_yaml_str(self, node):
  359. return self.construct_scalar(node)
  360. def construct_yaml_seq(self, node):
  361. data = []
  362. yield data
  363. data.extend(self.construct_sequence(node))
  364. def construct_yaml_map(self, node):
  365. data = {}
  366. yield data
  367. value = self.construct_mapping(node)
  368. data.update(value)
  369. def construct_yaml_object(self, node, cls):
  370. data = cls.__new__(cls)
  371. yield data
  372. if hasattr(data, '__setstate__'):
  373. state = self.construct_mapping(node, deep=True)
  374. data.__setstate__(state)
  375. else:
  376. state = self.construct_mapping(node)
  377. data.__dict__.update(state)
  378. def construct_undefined(self, node):
  379. raise ConstructorError(None, None,
  380. "could not determine a constructor for the tag %r" % node.tag,
  381. node.start_mark)
  382. SafeConstructor.add_constructor(
  383. 'tag:yaml.org,2002:null',
  384. SafeConstructor.construct_yaml_null)
  385. SafeConstructor.add_constructor(
  386. 'tag:yaml.org,2002:bool',
  387. SafeConstructor.construct_yaml_bool)
  388. SafeConstructor.add_constructor(
  389. 'tag:yaml.org,2002:int',
  390. SafeConstructor.construct_yaml_int)
  391. SafeConstructor.add_constructor(
  392. 'tag:yaml.org,2002:float',
  393. SafeConstructor.construct_yaml_float)
  394. SafeConstructor.add_constructor(
  395. 'tag:yaml.org,2002:binary',
  396. SafeConstructor.construct_yaml_binary)
  397. SafeConstructor.add_constructor(
  398. 'tag:yaml.org,2002:timestamp',
  399. SafeConstructor.construct_yaml_timestamp)
  400. SafeConstructor.add_constructor(
  401. 'tag:yaml.org,2002:omap',
  402. SafeConstructor.construct_yaml_omap)
  403. SafeConstructor.add_constructor(
  404. 'tag:yaml.org,2002:pairs',
  405. SafeConstructor.construct_yaml_pairs)
  406. SafeConstructor.add_constructor(
  407. 'tag:yaml.org,2002:set',
  408. SafeConstructor.construct_yaml_set)
  409. SafeConstructor.add_constructor(
  410. 'tag:yaml.org,2002:str',
  411. SafeConstructor.construct_yaml_str)
  412. SafeConstructor.add_constructor(
  413. 'tag:yaml.org,2002:seq',
  414. SafeConstructor.construct_yaml_seq)
  415. SafeConstructor.add_constructor(
  416. 'tag:yaml.org,2002:map',
  417. SafeConstructor.construct_yaml_map)
  418. SafeConstructor.add_constructor(None,
  419. SafeConstructor.construct_undefined)
  420. class FullConstructor(SafeConstructor):
  421. def construct_python_str(self, node):
  422. return self.construct_scalar(node)
  423. def construct_python_unicode(self, node):
  424. return self.construct_scalar(node)
  425. def construct_python_bytes(self, node):
  426. try:
  427. value = self.construct_scalar(node).encode('ascii')
  428. except UnicodeEncodeError as exc:
  429. raise ConstructorError(None, None,
  430. "failed to convert base64 data into ascii: %s" % exc,
  431. node.start_mark)
  432. try:
  433. if hasattr(base64, 'decodebytes'):
  434. return base64.decodebytes(value)
  435. else:
  436. return base64.decodestring(value)
  437. except binascii.Error as exc:
  438. raise ConstructorError(None, None,
  439. "failed to decode base64 data: %s" % exc, node.start_mark)
  440. def construct_python_long(self, node):
  441. return self.construct_yaml_int(node)
  442. def construct_python_complex(self, node):
  443. return complex(self.construct_scalar(node))
  444. def construct_python_tuple(self, node):
  445. return tuple(self.construct_sequence(node))
  446. def find_python_module(self, name, mark, unsafe=False):
  447. if not name:
  448. raise ConstructorError("while constructing a Python module", mark,
  449. "expected non-empty name appended to the tag", mark)
  450. if unsafe:
  451. try:
  452. __import__(name)
  453. except ImportError as exc:
  454. raise ConstructorError("while constructing a Python module", mark,
  455. "cannot find module %r (%s)" % (name, exc), mark)
  456. if not name in sys.modules:
  457. raise ConstructorError("while constructing a Python module", mark,
  458. "module %r is not imported" % name, mark)
  459. return sys.modules[name]
  460. def find_python_name(self, name, mark, unsafe=False):
  461. if not name:
  462. raise ConstructorError("while constructing a Python object", mark,
  463. "expected non-empty name appended to the tag", mark)
  464. if '.' in name:
  465. module_name, object_name = name.rsplit('.', 1)
  466. else:
  467. module_name = 'builtins'
  468. object_name = name
  469. if unsafe:
  470. try:
  471. __import__(module_name)
  472. except ImportError as exc:
  473. raise ConstructorError("while constructing a Python object", mark,
  474. "cannot find module %r (%s)" % (module_name, exc), mark)
  475. if not module_name in sys.modules:
  476. raise ConstructorError("while constructing a Python object", mark,
  477. "module %r is not imported" % module_name, mark)
  478. module = sys.modules[module_name]
  479. if not hasattr(module, object_name):
  480. raise ConstructorError("while constructing a Python object", mark,
  481. "cannot find %r in the module %r"
  482. % (object_name, module.__name__), mark)
  483. return getattr(module, object_name)
  484. def construct_python_name(self, suffix, node):
  485. value = self.construct_scalar(node)
  486. if value:
  487. raise ConstructorError("while constructing a Python name", node.start_mark,
  488. "expected the empty value, but found %r" % value, node.start_mark)
  489. return self.find_python_name(suffix, node.start_mark)
  490. def construct_python_module(self, suffix, node):
  491. value = self.construct_scalar(node)
  492. if value:
  493. raise ConstructorError("while constructing a Python module", node.start_mark,
  494. "expected the empty value, but found %r" % value, node.start_mark)
  495. return self.find_python_module(suffix, node.start_mark)
  496. def make_python_instance(self, suffix, node,
  497. args=None, kwds=None, newobj=False, unsafe=False):
  498. if not args:
  499. args = []
  500. if not kwds:
  501. kwds = {}
  502. cls = self.find_python_name(suffix, node.start_mark)
  503. if not (unsafe or isinstance(cls, type)):
  504. raise ConstructorError("while constructing a Python instance", node.start_mark,
  505. "expected a class, but found %r" % type(cls),
  506. node.start_mark)
  507. if newobj and isinstance(cls, type):
  508. return cls.__new__(cls, *args, **kwds)
  509. else:
  510. return cls(*args, **kwds)
  511. def set_python_instance_state(self, instance, state):
  512. if hasattr(instance, '__setstate__'):
  513. instance.__setstate__(state)
  514. else:
  515. slotstate = {}
  516. if isinstance(state, tuple) and len(state) == 2:
  517. state, slotstate = state
  518. if hasattr(instance, '__dict__'):
  519. instance.__dict__.update(state)
  520. elif state:
  521. slotstate.update(state)
  522. for key, value in slotstate.items():
  523. setattr(object, key, value)
  524. def construct_python_object(self, suffix, node):
  525. # Format:
  526. # !!python/object:module.name { ... state ... }
  527. instance = self.make_python_instance(suffix, node, newobj=True)
  528. yield instance
  529. deep = hasattr(instance, '__setstate__')
  530. state = self.construct_mapping(node, deep=deep)
  531. self.set_python_instance_state(instance, state)
  532. def construct_python_object_apply(self, suffix, node, newobj=False):
  533. # Format:
  534. # !!python/object/apply # (or !!python/object/new)
  535. # args: [ ... arguments ... ]
  536. # kwds: { ... keywords ... }
  537. # state: ... state ...
  538. # listitems: [ ... listitems ... ]
  539. # dictitems: { ... dictitems ... }
  540. # or short format:
  541. # !!python/object/apply [ ... arguments ... ]
  542. # The difference between !!python/object/apply and !!python/object/new
  543. # is how an object is created, check make_python_instance for details.
  544. if isinstance(node, SequenceNode):
  545. args = self.construct_sequence(node, deep=True)
  546. kwds = {}
  547. state = {}
  548. listitems = []
  549. dictitems = {}
  550. else:
  551. value = self.construct_mapping(node, deep=True)
  552. args = value.get('args', [])
  553. kwds = value.get('kwds', {})
  554. state = value.get('state', {})
  555. listitems = value.get('listitems', [])
  556. dictitems = value.get('dictitems', {})
  557. instance = self.make_python_instance(suffix, node, args, kwds, newobj)
  558. if state:
  559. self.set_python_instance_state(instance, state)
  560. if listitems:
  561. instance.extend(listitems)
  562. if dictitems:
  563. for key in dictitems:
  564. instance[key] = dictitems[key]
  565. return instance
  566. def construct_python_object_new(self, suffix, node):
  567. return self.construct_python_object_apply(suffix, node, newobj=True)
  568. FullConstructor.add_constructor(
  569. 'tag:yaml.org,2002:python/none',
  570. FullConstructor.construct_yaml_null)
  571. FullConstructor.add_constructor(
  572. 'tag:yaml.org,2002:python/bool',
  573. FullConstructor.construct_yaml_bool)
  574. FullConstructor.add_constructor(
  575. 'tag:yaml.org,2002:python/str',
  576. FullConstructor.construct_python_str)
  577. FullConstructor.add_constructor(
  578. 'tag:yaml.org,2002:python/unicode',
  579. FullConstructor.construct_python_unicode)
  580. FullConstructor.add_constructor(
  581. 'tag:yaml.org,2002:python/bytes',
  582. FullConstructor.construct_python_bytes)
  583. FullConstructor.add_constructor(
  584. 'tag:yaml.org,2002:python/int',
  585. FullConstructor.construct_yaml_int)
  586. FullConstructor.add_constructor(
  587. 'tag:yaml.org,2002:python/long',
  588. FullConstructor.construct_python_long)
  589. FullConstructor.add_constructor(
  590. 'tag:yaml.org,2002:python/float',
  591. FullConstructor.construct_yaml_float)
  592. FullConstructor.add_constructor(
  593. 'tag:yaml.org,2002:python/complex',
  594. FullConstructor.construct_python_complex)
  595. FullConstructor.add_constructor(
  596. 'tag:yaml.org,2002:python/list',
  597. FullConstructor.construct_yaml_seq)
  598. FullConstructor.add_constructor(
  599. 'tag:yaml.org,2002:python/tuple',
  600. FullConstructor.construct_python_tuple)
  601. FullConstructor.add_constructor(
  602. 'tag:yaml.org,2002:python/dict',
  603. FullConstructor.construct_yaml_map)
  604. FullConstructor.add_multi_constructor(
  605. 'tag:yaml.org,2002:python/name:',
  606. FullConstructor.construct_python_name)
  607. FullConstructor.add_multi_constructor(
  608. 'tag:yaml.org,2002:python/module:',
  609. FullConstructor.construct_python_module)
  610. FullConstructor.add_multi_constructor(
  611. 'tag:yaml.org,2002:python/object:',
  612. FullConstructor.construct_python_object)
  613. FullConstructor.add_multi_constructor(
  614. 'tag:yaml.org,2002:python/object/apply:',
  615. FullConstructor.construct_python_object_apply)
  616. FullConstructor.add_multi_constructor(
  617. 'tag:yaml.org,2002:python/object/new:',
  618. FullConstructor.construct_python_object_new)
  619. class UnsafeConstructor(FullConstructor):
  620. def find_python_module(self, name, mark):
  621. return super(UnsafeConstructor, self).find_python_module(name, mark, unsafe=True)
  622. def find_python_name(self, name, mark):
  623. return super(UnsafeConstructor, self).find_python_name(name, mark, unsafe=True)
  624. def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False):
  625. return super(UnsafeConstructor, self).make_python_instance(
  626. suffix, node, args, kwds, newobj, unsafe=True)
  627. # Constructor is same as UnsafeConstructor. Need to leave this in place in case
  628. # people have extended it directly.
  629. class Constructor(UnsafeConstructor):
  630. pass