Empty key validation

Sometimes you may wish to not specify a value or specify that it does not exist.

Using StrictYAML you can accept this as a valid value and have it parsed to one of three things - None, {} (empty dict), or [] (empty list).

Example yaml_snippet:

a:
from strictyaml import Map, Str, Enum, EmptyNone, EmptyDict, EmptyList, NullNone, load, as_document
from ensure import Ensure

EmptyNone with empty value:

Ensure(load(yaml_snippet, Map({"a": EmptyNone() | Enum(["A", "B",])}))).equals({"a": None})

EmptyDict:

Ensure(load(yaml_snippet, Map({"a": EmptyDict() | Enum(["A", "B",])}))).equals({"a": {}})

EmptyList:

Ensure(load(yaml_snippet, Map({"a": EmptyList() | Enum(["A", "B",])}))).equals({"a": []})

NullNone:

Ensure(load("a: null", Map({"a": NullNone() | Enum(["A", "B",])}))).equals({"a": None})

EmptyNone no empty value:

a: A
Ensure(load(yaml_snippet, Map({"a": EmptyNone() | Enum(["A", "B",])}))).equals({"a": "A"})

Combine Str with EmptyNone and Str is evaluated first:

Ensure(load(yaml_snippet, Map({"a": Str() | EmptyNone()}))).equals({"a": ""})

Combine EmptyNone with Str and Str is evaluated last:

Ensure(load(yaml_snippet, Map({"a": EmptyNone() | Str()}))).equals({"a": None})

Non-empty value:

a: C
load(yaml_snippet, Map({"a": Enum(["A", "B",]) | EmptyNone()}))
strictyaml.exceptions.YAMLValidationError:
when expecting an empty value
found arbitrary text
  in "<unicode string>", line 1, column 1:
    a: C
     ^ (line: 1)

Serialize empty dict:

print(as_document({"a": {}}, Map({"a": EmptyDict() | Str()})).as_yaml())
a:

Serialize empty list:

print(as_document({"a": []}, Map({"a": EmptyList() | Str()})).as_yaml())
a:

Serialize None:

print(as_document({"a": None}, Map({"a": EmptyNone() | Str()})).as_yaml())
a:

Executable specification

Documentation automatically generated from empty.story storytests.