在代码中从头开始构建 YAML 文档
如果未使用模式,则 YAML 文档可以由字典、列表和字符串的组合构建。
from ensure import Ensure
from strictyaml import as_document
from collections import OrderedDict
# Can also use regular dict if an arbitrary ordering is ok
yaml = as_document(OrderedDict(
[(u"â", 'yes'), ("b", "hâllo"), ("c", ["1", "2", "3"])]
))
然后转储
print(yaml.as_yaml())
â: yes
b: hâllo
c:
- 1
- 2
- 3
但是,任何不是字符串、字典或列表的类型都无法在没有模式的情况下解析
class RandomClass(object):
def __repr__(self):
return 'some random object'
as_document({"x": RandomClass()})
strictyaml.exceptions.YAMLSerializationError:
'some random object' is not a string
空字典也无法在没有模式的情况下序列化
as_document({'hello': {}})
strictyaml.exceptions.YAMLSerializationError:
Empty dicts are not serializable to StrictYAML unless schema is used.
列表也不行
as_document({'hello': []})
strictyaml.exceptions.YAMLSerializationError:
Empty lists are not serializable to StrictYAML unless schema is used.
你可以从被序列化的对象中获取行号
Ensure(yaml.start_line).equals(1)