Optional keys with defaults (Map/Optional)

Experimental

This feature is in alpha. The API may change on a minor version increment.

Example yaml_snippet:

a: 1
from strictyaml import Map, Int, Str, Bool, EmptyNone, Optional, load, as_document
from collections import OrderedDict
from ensure import Ensure

schema = Map({"a": Int(), Optional("b", default=False): Bool(), })

When parsed the result will include the optional value:

Ensure(load(yaml_snippet, schema).data).equals(OrderedDict([("a", 1), ("b", False)]))

If parsed and then output to YAML again the default data won't be there:

print(load(yaml_snippet, schema).as_yaml())
a: 1

When default data is output to YAML it is removed:

print(as_document({"a": 1, "b": False}, schema).as_yaml())
a: 1

When you want a key to stay and default to None:

schema = Map({"a": Int(), Optional("b", default=None, drop_if_none=False): EmptyNone() | Bool(), })
Ensure(load(yaml_snippet, schema).data).equals(OrderedDict([("a", 1), ("b", None)]))

Executable specification

Documentation automatically generated from optional-with-defaults.story storytests.