Saving settings in python with YAML (an XML alternative)

When transferring information or settings between computers and programs is is useful to use something simple and program independent. For a recent project I need to send a settings file between a PHP script and a python program, I needed something that would support trees so an INI file was out of the question, and I naturally thought of using XML, however when looking for more information I stumbled upon YAML (seemingly forgotten alternative to XML).

YAML is a recursive acronym that stands for YAML Ain’t Markup Language and below is a simplified example taken from the YAML site. The layout is similar to python with indents representing the nested layers. Semicolons are used to seperate variable names and value pairs.

name   : Joe Bloggs
    - sku         : BL394D
      quantity    : 4
      description : Basketball
      price       : 450.00
    - sku         : BL4438H
      quantity    : 1
      description : Super Hoop
      price       : 2392.00
tax  : 251.42
total: 4443.5

To use YAML in python you will need the PyYAML library avaliable here or in via your package manager in linux. (I.E. “sudo apt-get install https://pyyaml.org/wiki/PyYAML” in ubuntu/debian).

The code for then using YAML is very simple, first we import the yaml library, then we open our settings file we have created and then use yaml’s load feature to load our settings into a python dictionary, and then finally printing it out so we can see what it contains

import yaml
print settings

Using the example YAML file above saved to settings.cfg this python script will output the following when run:

{'product': [{'sku': 'BL394D', 'price': 450.0, 'description': 
'Basketball', 'quantity': 4}, {'sku': 'BL4438H', 'price': 2392.0, 
'description': 'Super Hoop', 'quantity': 1}], 'total': 4443.5, 'tax':
251.41999999999999, 'name': 'Joe Bloggs'}

We can now access all the information in the file very easily (I.E. settings[‘name’] will give us the name Joe Bloggs).

YAML supports much much more than what is discussed here and further information can be found on the YAML website.

Read More