yaml

What is the << (double left arrow) syntax in YAML called, and where's it specified?


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 specification for << reveals that it doesn't appear anywhere in the specification. Yet it's supported by, at the very least, PyYAML and Online YAML Parser.

What is this syntax, and how come it doesn't seem to appear in the specification?


Solution

  • It is called the Merge Key Language-Independent Type for YAML version 1.1. and specified here.

    It is something that parsers can optionally support, and 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.