fredrik fredrik - 2 months ago 20
Python Question

How can I use references in YAML?

I have this YAML:

app_name: my_app
version:
1.0:
path: /my_app/1.0
2.0:
path: /my_app/2.0


Is it possible to somehow avoid typing out "my_app" and its version and instead read that from the YAML itself by using some sort of referencing?

I had something like this in mind:

app_name: my_app
version:
1.0:
path: /@app_name/$key[-1]
2.0:
path: /@app_name/$key[-1]


In the end, I intend to read this into a Python dictionary.

Answer

There is no mechanism in YAML that does substitution on substrings of scalars, the best you have are anchors and aliases, and they refer to whole scalars or collections (mappings, sequences).

If you want to do such thing you will have to do the substitution after parsing in the YAML, interpreting the various values and rebuilding the data structure.

There are several examples (including here on [so]) of substitution where some part of the YAML is used as dictionary to replace other parts. When you do that you can parse the YAML input once, substitute on the source, and reparse the output of that substitution. Because you use relative references, that will not work for you and you would need to do the substitution in the parsed tree. The alternative is modifying the parser to strip the @ from inputs and do this on the fly.

In both cases it would be a bad idea to use the same token (@) for marking a key to "store" its value (@app_name), as well as marking a key to store the key itself (@1.0), and for using the associated value (which you do in two completely different ways @app_name and @key[-1]).