ruamel.yaml is a YAML 1.2 loader/dumper package for Python. It is a derivative of Kirill Simonov’s PyYAML 3.11
ruamel.yaml supports YAML 1.2 and has round-trip loaders and dumpers that preserves, among others:
idNNN
)You can read more at http://yaml.readthedocs.io/en/latest/overview.html
In [1]:
import ruamel.yaml
In [2]:
ruamel.yaml
Out[2]:
In [3]:
ruamel
Out[3]:
In [4]:
dir(ruamel)
Out[4]:
In [6]:
inp = """\
# example
name:
# details
family: Goda # Very uncommon
given: Satish # One of the siblings (Comman name)
"""
In [7]:
print(inp)
In [8]:
help(ruamel.yaml.load)
In [9]:
code = ruamel.yaml.load(inp, Loader=ruamel.yaml.RoundTripLoader)
In [10]:
code
Out[10]:
In [11]:
code['name']['given']
Out[11]:
In [12]:
code['name']['family']
Out[12]:
In [13]:
import ruamel.yaml
inp = """\
- &CENTER {x: 1, y: 2}
- &LEFT {x: 0, y: 2}
- &BIG {r: 10}
- &SMALL {r: 1}
"""
In [14]:
code = ruamel.yaml.load(inp, Loader=ruamel.yaml.RoundTripLoader)
In [15]:
code
Out[15]:
In [16]:
type(code)
Out[16]:
In [17]:
dir(code)
Out[17]:
In [18]:
code.anchor
Out[18]:
In [19]:
code.anchor.value
In [20]:
code.keys()
In [21]:
for item in code:
print(item)
In [22]:
for item in code:
print(item.anchor.value, item.keys())
In [23]:
import ruamel.yaml
inp = """\
- &CENTER {x: 1, y: 2}
- &LEFT {x: 0, y: 2}
- &BIG {r: 10}
- &SMALL {r: 1}
# All the following maps are equal:
# Explicit keys
- x: 1
y: 2
r: 10
label: center/big
# Merge one map
- <<: *CENTER
r: 10
label: center/big
# Merge multiple maps
- <<: [*CENTER, *BIG]
label: center/big
# Override
- <<: [*BIG, *LEFT, *SMALL]
x: 1
label: center/big
"""
In [24]:
data = ruamel.yaml.load(inp, Loader=ruamel.yaml.RoundTripLoader)
In [25]:
data
Out[25]:
In [26]:
# Modifying the merge order of the aliases
inp = """\
- &CENTER {x: 1, y: 2}
- &LEFT {x: 0, y: 2}
- &BIG {r: 10}
- &SMALL {r: 1}
# All the following maps are equal:
# Explicit keys
- x: 1
y: 2
r: 10
label: center/big
# Merge one map
- <<: *CENTER
r: 10
label: center/big
# Merge multiple maps
- <<: [*CENTER, *BIG]
label: center/big
# Override
- <<: [*SMALL, *BIG, *LEFT]
x: 1
label: center/small
"""
In [27]:
data = ruamel.yaml.load(inp, Loader=ruamel.yaml.RoundTripLoader)
In [28]:
data
Out[28]:
In [29]:
assert data[7]['y'] == 2
In [30]:
yaml_str = """\
first_name: Art
occupation: Architect # This is an occupation comment
about: Art Vandelay is a fictional character that George invents...
"""
data = ruamel.yaml.round_trip_load(yaml_str)
In [31]:
data
Out[31]:
In [32]:
data.insert(1, 'last name', 'Vandelay', comment='new key')
In [33]:
print(ruamel.yaml.round_trip_dump(data))