| 1 |
Optional keys with defaults (Map/Optional): |
| 2 |
docs: compound/optional-keys-with-defaults |
| 3 |
experimental: yes |
| 4 |
based on: strictyaml |
| 5 |
about: | |
| 6 |
Not every key in a YAML mapping will be required. If |
| 7 |
you use the "Optional('key')" validator with YAML, |
| 8 |
you can signal that a key/value pair is not required. |
| 9 |
given: |
| 10 |
yaml_snippet: | |
| 11 |
a: 1 |
| 12 |
setup: | |
| 13 |
from strictyaml import Map, Int, Str, Bool, EmptyNone, Optional, load, as_document |
| 14 |
from collections import OrderedDict |
| 15 |
from ensure import Ensure |
| 16 |
|
| 17 |
schema = Map({"a": Int(), Optional("b", default=False): Bool(), }) |
| 18 |
variations: |
| 19 |
When parsed the result will include the optional value: |
| 20 |
steps: |
| 21 |
- Run: | |
| 22 |
Ensure(load(yaml_snippet, schema).data).equals(OrderedDict([("a", 1), ("b", False)])) |
| 23 |
|
| 24 |
If parsed and then output to YAML again the default data won't be there: |
| 25 |
steps: |
| 26 |
- Run: |
| 27 |
code: print(load(yaml_snippet, schema).as_yaml()) |
| 28 |
will output: |- |
| 29 |
a: 1 |
| 30 |
|
| 31 |
When default data is output to YAML it is removed: |
| 32 |
steps: |
| 33 |
- Run: |
| 34 |
code: | |
| 35 |
print(as_document({"a": 1, "b": False}, schema).as_yaml()) |
| 36 |
will output: |- |
| 37 |
a: 1 |
| 38 |
|
| 39 |
When you want a key to stay and default to None: |
| 40 |
steps: |
| 41 |
- Run: |
| 42 |
code: | |
| 43 |
schema = Map({"a": Int(), Optional("b", default=None, drop_if_none=False): EmptyNone() | Bool(), }) |
| 44 |
Ensure(load(yaml_snippet, schema).data).equals(OrderedDict([("a", 1), ("b", None)])) |
| 45 |
|
| 46 |
|
| 47 |
Optional keys with bad defaults: |
| 48 |
based on: Optional keys with defaults (Map/Optional) |
| 49 |
steps: |
| 50 |
- Run: |
| 51 |
code: | |
| 52 |
Map({"a": Int(), Optional("b", default="nonsense"): Bool(), }) |
| 53 |
raises: |
| 54 |
type: strictyaml.exceptions.InvalidOptionalDefault |
| 55 |
message: "Optional default for 'b' failed validation:\n Not a boolean" |
| 56 |
|
| 57 |
|
| 58 |
Optional keys revalidation bug: |
| 59 |
based on: Optional keys with defaults (Map/Optional) |
| 60 |
given: |
| 61 |
yaml_snippet: | |
| 62 |
content: |
| 63 |
subitem: |
| 64 |
a: 1 |
| 65 |
steps: |
| 66 |
- Run: |
| 67 |
code: | |
| 68 |
from strictyaml import MapPattern, Any |
| 69 |
|
| 70 |
loose_schema = Map({"content": Any()}) |
| 71 |
strict_schema = Map({"subitem": Map({"a": Int(), Optional("b", default=False): Bool()})}) |
| 72 |
|
| 73 |
myyaml = load(yaml_snippet, loose_schema) |
| 74 |
myyaml['content'].revalidate(strict_schema) |
| 75 |
assert myyaml.data == {"content": {"subitem": {"a": 1, "b": False}}}, myyaml.data |
| 76 |
print(myyaml.data.__repr__()) |
| 77 |
will output: "{'content': {'subitem': {'a': 1, 'b': False}}}" |