Installation
Install the PyYAML package via pip:
python3 -m pip install pyyaml
Loading a YAML File
The safest way to load a YAML document is with safe_load():
import yaml
data = yaml.safe_load(open('./data.yaml'))
YAML Syntax Essentials
- Case-sensitive –
Trueandtrueare different. - Indentation – Spaces matter only for alignment; same-level eleemnts must be left-aligned.
- Comments – Lines starting with
#are comments.
Lists
A list is indicated by a dash followed by a space:
-
- 10
- 10
-
- 20
- 30
The above YAML produces the Python list: [[10, 10], [20, 30]].
Nested lists example:
-
- [1, 2]
- [2, 3]
Results in: [[[1, 2], [2, 3]]].
Dictionaries
Key-value pairs are written as key: value. Nested dictionaries use deeper indentation:
key:
child1: value1
child2: value2
Yields: {'key': {'child1': 'value1', 'child2': 'value2'}}.
Nested Structures (List of Dictionaries)
key:
- id: 1
name: lijia
price: 100
- id: 2
name: litian
price: 200
Parsed as: {'key': [{'id': 1, 'name': 'lijia', 'price': 100}, {'id': 2, 'name': 'litian', 'price': 200}]}.
Mixed Types
name:
- lijia
- litian
- lijiajia
age:
lijia: 30
litian: 28
lijiajia: 33
Produces: {'name': ['lijia', 'litian', 'lijiajia'], 'age': {'lijia': 30, 'litian': 28, 'lijiajia': 33}}.
Practical Example: Parameterzied Tests with pytest
Use YAML to store test data and load it directly via yaml.safe_load():
import pytest
import yaml
# data.yaml content example:
# - ['3+5', 8]
# - ['2+5', 7]
# - ['7+5', 30]
@pytest.mark.parametrize('expression,expected', yaml.safe_load(open('./data.yaml')))
def test_eval_expression(expression, expected):
assert eval(expression) == expected
Verifying YAML Data Outside pytest
To inspect what the YAML file actual contains, run a simple script:
import yaml
with open('./data.yaml') as file:
parsed = yaml.safe_load(file)
print(parsed)