YAML in Python with PyYAML

PyYAML is an excellent and popular YAML parser for python allowing you to read and write YAML.

Read

You can use the yaml.load() method to parse a YAML string into python object representation. For example:

import yaml

users_yaml = """
  - name: John
    age: 27
    occupation: doctor
  - name: Jane
    age: 26
    occupation: lawyer
"""
users = yaml.load(users_yaml)

Will set the users variable equal to the following list:

[{name: ‘John’, age: 27, occupation: ‘doctor’}, {name: Jane, age: 26, occupation: lawyer}]

You can also use yaml.load() to read from a .yaml file like so:

import yaml

file_stream = file(‘users.yaml’, ‘r’)
users = yaml.load(file_stream)

You can even populate instances of classes by using the !!python/object tag notation:

import yaml
class User:

def __init__(self, name, age, occupation):
  self.name = name
  self.age = age
  self.occupation = occupation

john_yaml = """
!!python/object:__main__.User
name: John
age: 27
occupation: doctor
"""

john = yaml.load(john_yaml)

Will result in john being a fully populated instance of your User class!

Write

You can use the yaml.dump() method to parse a python object and turn it into YAML.

import yaml

john = {
  ‘name’: ‘John’,
  ‘age’: 27,
  ‘occupation’: ‘doctor’
}

john_yaml = yaml.dump(john)

john_yaml will be a YAML string representation of your object:

name: John
age: 27
occupation: doctor

You can also direct yaml.dump() to write to a file:

import yaml
john = {
  ‘name’: ‘John’,
  ‘age’: 27,
  ‘occupation’: ‘doctor’
}

stream = file(‘john.yaml’, ‘w’)
yaml.dump(john, stream)

yaml.dump() can also accept an instance of a class:

import yaml

john = User(‘John’, 27, ‘doctor’)
stream = file(‘john.yaml’, ‘w’)
yaml.dump(john, stream)

Those are the basics, but you can find much more detail in the PyYAML documentation!

%d bloggers like this: