I don't understand what a YAML tag is
Solution 1:
I don't know a lot about YAML but I'll give it a shot:
Tags are used to denote types. A tag is declared using !
as you have seen from the "refcard" there. The %TAG
directive is kind of like declaring a shortcut to a tag.
I'll demonstrate with PyYaml. PyYaml can parse the secondary tag of !!python/object:
as an actual python object. The double exclamation mark is a substitution in itself, short for !tag:yaml.org,2002:
, which turns the whole expression into !tag:yaml.org,2002:python/object:
. This expression is a little unwieldy to be typing out every time we want to create an object, so we give it an alias using the %TAG
directive:
%TAG !py! tag:yaml.org,2002:python/object: # declares the tag alias
---
- !py!__main__.MyClass # creates an instance of MyClass
- !!python/object:__main__.MyClass # equivalent with no alias
- !<tag:yaml.org,2002:python/object:__main__.MyClass> # equivalent using primary tag
Nodes are parsed by their default type if you have no tag annotations. The following are equivalent:
- 1: Alex
- !!int "1": !!str "Alex"
Here is a complete Python program using PyYaml demonstrating tag usage:
import yaml
class Entity:
def __init__(self, idNum, components):
self.id = idNum
self.components = components
def __repr__(self):
return "%s(id=%r, components=%r)" % (
self.__class__.__name__, self.id, self.components)
class Component:
def __init__(self, name):
self.name = name
def __repr__(self):
return "%s(name=%r)" % (
self.__class__.__name__, self.name)
text = """
%TAG !py! tag:yaml.org,2002:python/object:__main__.
---
- !py!Component &transform
name: Transform
- !!python/object:__main__.Component &render
name: Render
- !<tag:yaml.org,2002:python/object:__main__.Entity>
id: 123
components: [*transform, *render]
- !<tag:yaml.org,2002:int> "3"
"""
result = yaml.load(text)
More information is available in the spec