Build a YAML document from scratch in code

YAML documents can be built from combinations of dicts, lists and strings if no schema is used.

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"])]

Then dump:

â: yes
b: hâllo
- 1
- 2
- 3

However, any type that is not a string, dict or list cannot be parsed without a schema:

class RandomClass(object):
    def __repr__(self):
        return 'some random object'

as_document({"x": RandomClass()})
'some random object' is not a string

Empty dicts also cannot be serialized without a schema:

as_document({'hello': {}})
Empty dicts are not serializable to StrictYAML unless schema is used.

Neither can lists:

as_document({'hello': []})
Empty lists are not serializable to StrictYAML unless schema is used.

You can grab line numbers from the object that is serialized:


Executable specification

Documentation automatically generated from build-yaml-document-from-scratch.story storytests.