gschizas gschizas - 19 days ago 4
YAML Question

Is it possible to have aliases in a multi-document YAML stream that span all documents?

This is what I'm trying to do (code is in Python 3):

import ruamel.yaml as yaml
from print import pprint

yaml_document_with_aliases = """
title: test
choices: &C
a: one
b: two
c: three
---
title: test 2
choices: *C
"""

items = list(yaml.load_all(yaml_document_with_aliases))


The result is:

ComposerError: found undefined alias 'C'


When I'm using a non-document-based YAML file, this works as expected:

import ruamel.yaml as yaml
from print import pprint

yaml_nodes_with_aliases = """
-
title: test
choices: &C
a: one
b: two
c: three
-
title: test 2
choices: *C
"""

items = yaml.load(yaml_nodes_with_aliases)

pprint(items)


Result:

[{'choices': {'a': 'one', 'b': 'two', 'c': 'three'}, 'title': 'test'},
{'choices': {'a': 'one', 'b': 'two', 'c': 'three'}, 'title': 'test 2'}]


(what I wanted to accomplish anyway)

Answer

The problem here is that:

title: test
choices: &C
  a: one
  b: two
  c: three
---
title: test 2
choices: *C

is not a document, these are two YAML documents in one file. The anchor definition &C doesn't carry from one YAML document to another, it can only be used up until the document separator ---.