我正在尝试在 python 中创建一个创建自定义 python 对象的 yaml 序列。该对象需要使用在__init__
. 然而,construct_mapping 函数似乎并没有构建嵌入序列(列表)和字典的整个树。
考虑以下:
import yaml
class Foo(object):
def __init__(self, s, l=None, d=None):
self.s = s
self.l = l
self.d = d
def foo_constructor(loader, node):
values = loader.construct_mapping(node)
s = values["s"]
d = values["d"]
l = values["l"]
return Foo(s, d, l)
yaml.add_constructor(u'!Foo', foo_constructor)
f = yaml.load('''
--- !Foo
s: 1
l: [1, 2]
d: {try: this}''')
print(f)
# prints: 'Foo(1, {'try': 'this'}, [1, 2])'
这很好用,因为f
保存了对l
和对象的引用,这些对象在创建对象后d
实际上填充了数据。Foo
现在,让我们做一些更复杂的事情:
class Foo(object):
def __init__(self, s, l=None, d=None):
self.s = s
# assume two-value list for l
self.l1, self.l2 = l
self.d = d
现在我们得到以下错误
Traceback (most recent call last):
File "test.py", line 27, in <module>
d: {try: this}''')
File "/opt/homebrew/lib/python2.7/site-packages/yaml/__init__.py", line 71, in load
return loader.get_single_data()
File "/opt/homebrew/lib/python2.7/site-packages/yaml/constructor.py", line 39, in get_single_data
return self.construct_document(node)
File "/opt/homebrew/lib/python2.7/site-packages/yaml/constructor.py", line 43, in construct_document
data = self.construct_object(node)
File "/opt/homebrew/lib/python2.7/site-packages/yaml/constructor.py", line 88, in construct_object
data = constructor(self, node)
File "test.py", line 19, in foo_constructor
return Foo(s, d, l)
File "test.py", line 7, in __init__
self.l1, self.l2 = l
ValueError: need more than 0 values to unpack
这是因为 yaml 构造函数是在嵌套之前的外层开始,在所有节点完成之前构造对象。有没有办法颠倒顺序并首先从深度嵌入(例如嵌套)对象开始?或者,有没有办法至少在加载节点的对象之后进行构造?