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:

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

EmptyNone with empty value:

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


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


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

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()}))
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())

Serialize empty list:

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

Serialize None:

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

Executable specification

Page automatically generated from empty.story.