What is the << (double left arrow) syntax in YAML called, and where's it specced?
The <<:
operator in YAML is usable to import the contents of one mapping into another, similarly to the **
double-splat operator in Python or ...
object destructuring operator in JavaScript. For example,
foo:
a: b
<<:
c: d
e: f
is equivalent to
foo:
a: b
c: d
e: f
This is useful when used along with node anchors to include some common default properties in many objects, as illustrated in, for example, the Learn YAML in Y minutes tutorial:
# Anchors can be used to duplicate/inherit properties base: &base name: Everyone has same name foo: &foo <<: *base age: 10 bar: &bar <<: *base age: 20
However, I am confused about where this syntax comes from or why it works. CTRL+Fing the YAML spec for <<
reveals that it doesn't appear anywhere in the spec. Yet it's supported by, at the very least, PyYAML and http://yaml-online-parser.appspot.com/.
What is this syntax, and how come it doesn't seem to appear in the spec?
Solution 1:
It is called the Merge Key Language-Independent Type for YAML version 1.1. and specced here
It is something that parsers can optionally support, it is essentially an interpretation of the key-value pair with the special key <<
, where the value is either a mapping (usually indicated via an alias as in the spec, and although that doesn't seem to be required, it makes little sense not to use an alias) or a list of mappings (i.e. aliases of mappings), and gets interpreted in a special way.
Solution 2:
To add on to other answers:
IMO, the example from "Learn yaml in Y Minutes" is incomplete because it doesn't show what happens when the keys are the same. For example:
base: &base
name: Everyone has same name
age: 5
foo: &foo
<<: *base
bar: &bar
<<: *base
age: 20
For the bottom two items yields:
foo:
name: Everyone has same name
age: 5
bar:
name: Everyone has same name
age: 20
bar
overrides the age while foo
does not. According to the spec the entries of the object merging in have a lower priority than those on the object receiving them.
The “<<” merge key is used to indicate that all the keys of one or more specified maps should be inserted into the current map. If the value associated with the key is a single mapping node, each of its key/value pairs is inserted into the current mapping, unless the key already exists in it.