File: optional-keys-with-defaults.md

package info (click to toggle)
python-strictyaml 1.7.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,708 kB
  • sloc: python: 12,836; sh: 48; makefile: 3
file content (90 lines) | stat: -rw-r--r-- 1,406 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
---
title: Optional keys with defaults (Map/Optional)
---

!!! warning "Experimental"

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




Example yaml_snippet:

```yaml
a: 1

```


```python
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:


```python
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:


```python
print(load(yaml_snippet, schema).as_yaml())
```

```yaml
a: 1
```




When default data is output to YAML it is removed:


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

```

```yaml
a: 1
```




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


```python
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)]))

```







!!! note "Executable specification"

    Documentation automatically generated from 
    <a href="https://github.com/crdoconnor/strictyaml/blob/master/hitch/story/optional-with-defaults.story">optional-with-defaults.story
    storytests.