Welcome, guest | Sign In | My Account | Store | Cart

This recipe shows how one can add include support to applications that use PyYAML.

Python, 7 lines
1
2
3
4
5
6
7
import yaml

def yaml_include(loader, node):
    with file(node.value) as inputfile:
        return yaml.load(inputfile)

yaml.add_constructor("!include", yaml_include)

After running this recipe, you can load files that include a !include tag, e.g.:

- foo: 123
  bar: !include otherfile.yaml
- baz: 456

When you load such a file, the !include otherfile.yaml part will be replaced by the data in the other YAML file.

Be aware that this method is insecure and unsafe by all means. The file path is not checked in any way, runtime exceptions might occur (e.g. if the file is not found) and users can produce endless recursions by including a file in itself. Never load YAML files from untrusted sources that way.

Also, unfortunately you can not use it in combination with the merge key (<< :) technique. This is a limitation of the merge key semantics.