Posted by virantha on Wed 04 September 2013

PyYAML: Include yaml files within yaml files

The official YAML spec doesn't support embedding external files inside a YAML file, a feature that can be extremely useful for maintenance of long/complex YAML files. I found this great code snippet yaml-include-snippet for including other YAML files in your top-level YAML.

However, the code above assumes the include path is relative to the script invocation path, when it's more likely that you want to refer to your sub-YAML files relative to the top-level YAML file. So, here's my small modification to enable this:

def yaml_include(loader, node):
    # Get the path out of the yaml file
    file_name = os.path.join(os.path.dirname(, node.value)

    with file(file_name) as inputfile:
        return yaml.load(inputfile)

yaml.add_constructor("!include", yaml_include)

© Virantha Ekanayake. Built using Pelican. Modified svbhack theme, based on theme by Carey Metcalfe