summaryrefslogtreecommitdiffstats
path: root/_doc/basicuse.ryd
blob: cce50d84968c53fbc92fa0bcabc28f2bf449b1bb (plain)
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
version: 0.2
text: md
pdf: false
--- !python-pre |
import sys
from io import StringIO
from ruamel.yaml import YAML
yaml=YAML()
s = StringIO()
doc = "a: 1"
data = dict(a=1)
--- |
# Basic Usage
## Load and dump  

You load a YAML document using:
--- !python |
from ruamel.yaml import YAML

yaml=YAML(typ='safe')   # default, if not specfied, is 'rt' (round-trip)
yaml.load(doc)

--- |
in this `doc` can be a file pointer (i.e. an object that has the
`.read()` method, a string or a `pathlib.Path()`. `typ='safe'`
accomplishes the same as what `safe_load()` did before: loading of a
document without resolving unknown tags. Provide `pure=True` to enforce
using the pure Python implementation, otherwise the faster C libraries
will be used when possible/available but these behave slightly different
(and sometimes more like a YAML 1.1 loader).

Dumping works in the same way:
--- !code |
from ruamel.yaml import YAML

yaml=YAML()
yaml.default_flow_style = False
yaml.dump({'a': [1, 2]}, s)
--- |
in this `s` can be a file pointer (i.e. an object that has the
`.write()` method, or a `pathlib.Path()`. If you want to display your
output, just stream to `sys.stdout`.

If you need to transform a string representation of the output provide a
function that takes a string as input and returns one:
--- !python |
def tr(s):
    return s.replace('\n', '<\n')  # such output is not valid YAML!

yaml.dump(data, sys.stdout, transform=tr)

--- |
## More examples

Using the C based SafeLoader (at this time is inherited from
libyaml/PyYAML and e.g. loads `0o52` as well as `052` as integer
`42`):
--- !python |
   from ruamel.yaml import YAML

   yaml=YAML(typ="safe")
   yaml.load("""a:\n  b: 2\n  c: 3\n""")

--- |
Using the Python based SafeLoader (YAML 1.2 support, `052` loads as
`52`):
--- !python |
   from ruamel.yaml import YAML

   yaml=YAML(typ="safe", pure=True)
   yaml.load("""a:\n  b: 2\n  c: 3\n""")

--- |

Restrictions when using the C based SafeLoader/SafeDumper:

- yaml.indent will set the same value for mappings and sequences. (Issue 471)