Tutorial¶
Reading YAML¶
The function rjgtoys.yaml.yaml_load()
will read YAML.
It can read a string:
from rjgtoys.yaml import yaml_load
data = yaml_load("""
---
a: 1
b: 2
""")
print(data)
Or an input stream:
import os
from rjgtoys.yaml import yaml_load
path = os.path.join(os.path.dirname(__file__), 'tutorial2.yaml')
with open(path, 'r') as src:
data = yaml_load(src)
print(data)
Reading from a file can be done directly with rjgtoys.yaml.yaml_load_path()
:
import os
from rjgtoys.yaml import yaml_load_path
path = os.path.join(os.path.dirname(__file__), 'tutorial2.yaml')
data = yaml_load_path(path)
print(data)
If yaml_load_path()
is passed a path to a directory, it
will return a list in which each item is the content of a file loaded from
that directory (but in no particular order, and with no indication of where the
content came from).
Using the data¶
Mappings returned from the loader functions are rjgtoys.thing.Thing
instances, which means they treat attribute and item access equivalently,
and so you can do things like this:
from rjgtoys.yaml import yaml_load
data = yaml_load("""
top:
first: 1
second: 2
inner:
a: hello
b: world
""")
assert data.top.first + data.top.second == 3
greeting = "%s, %s" % (data.top.inner.a, data.top.inner.b)
print(greeting)
See also: rjgtoys.thing
Referencing other files¶
An !include path tag in YAML input will be replaced by the data loaded from the specified path (or a list, if the path specifies a directory).
Paths in !include tags are interpreted relative to the directory of the file that contains the tag, or (if reading from a string or other stream with no associated directory) the current working directory.
Here’s an example of an !include:
---
tutorial2: !include tutorial2.yaml
tutorial5: 'more data'
Writing YAML¶
The function rjgtoys.yaml.yaml_dump()
converts an object into YAML
and writes it to an output stream. The default output stream is sys.stdout.
from rjgtoys.yaml import yaml_dump
data = dict(
a=1,
b=2,
inner=dict(
part1="part 1",
part2="part 2",
items=[1,2,3,4]
)
)
yaml_dump(data)
The output should look like this:
a: 1
b: 2
inner:
items:
- 1
- 2
- 3
- 4
part1: part 1
part2: part 2