Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24590

Is it valid YAML to place two anchors in the same name

This is my YAML

a: &SS Moyshale
b:  *SS
c: &SS Moyshale2
d:  *SS

Is this a valid YAML? (I want d to be equal to Moyshale2)

Upvotes: 3

Views: 2104

Answers (1)

Anthon
Anthon

Reputation: 76598

Yes that is valid YAML, according to the YAML 1.2 specification:

When composing a representation graph from serialized events, an alias node refers to the most recent node in the serialization having the specified anchor. Therefore, anchors need not be unique within a serialization.

And therefore d should equal the most recent "definition" of SS.

Some parsers will throw a warning, which you would have to filter out:

import sys
import warnings
import ruamel.yaml

yaml_str = """\
a: &SS Moyshale
b:  *SS
c: &SS Moyshale2
d:  *SS
"""

with warnings.catch_warnings():             # ignore the re
    warnings.simplefilter('ignore')
    data = ruamel.yaml.round_trip_load(yaml_str)
ruamel.yaml.round_trip_dump(data, sys.stdout)

You would get the following output and:

a: Moyshale
b: Moyshale
c: Moyshale2
d: Moyshale2

Without the filter you would also get:

..../lib/python3.5/site-packages/ruamel/yaml/composer.py:98: ReusedAnchorWarning: 
found duplicate anchor 'SS'
first occurence   in "<unicode string>", line 1, column 4:
    a: &SS Moyshale
       ^
second occurence   in "<unicode string>", line 3, column 4:
    c: &SS Moyshale2
       ^
  warnings.warn(ws, ReusedAnchorWarning)

Please note that aliases on string scalars are (currently) not preserved in ruamel.yaml¹ and since the anchors have no associated aliases, they are not included in the output. If you change Moyshale and Moyshale2 to [Moyshale] and [Moyshale2] the output would include the anchor SS twice:

a: &SS [Moyshale]
b: *SS
c: &SS [Moyshale2]
d: *SS

¹ This was done using ruamel.yaml a YAML 1.2 parser, of which I am the author.

Upvotes: 4

Related Questions