问题
I am trying to combine anchors and aliases in order to reuse values into several containers, under different names.
I tried the following code:
FWL_GV_NANSEN: &fwl_gv_nansen
dtype: float
value: 2715.0
FWL_GV_E3_2: &fwl_gv_e32 *fwl_gv_nansen
the goal is simply to have another variable FWL_GV_E3_2 containing the same information than FWL_GV_NANSEN that I could refer to later on.
Just the same than defining in Python (or other):
a = 5.0
b = a
c = b
But this triggers the following error message:
yaml.parser.ParserError: while parsing a block mapping in "fwl_2.yml", line 7, column 3 expected < block end >, but found '< alias >'
Is there no way to assign the content of aliases to variable used to defined a new anchor (propagating the initial values through different variables?
PS: maybe YAML is not the best language for this since it would be trivial using python's variables for example but I have to use YAML
回答1:
The YAML node properties (i.e. tags and anchors) can only occur on "real" nodes: collections (block or flow) or scalars.
You can see from the production rules that c-ns-properties
can be used only there, but section for aliases also states explicitly:
Note that an alias node must not specify any properties [...]
What is possible if your YAML parser gives you access to the original anchor/aliases, or some anchor-to-node/object mapping (such as my ruamel.yaml
package for Python when used for round-tripping), is to use a tagged scalar:
FWL_GV_NANSEN: &fwl_gv_nansen
dtype: float
value: 2715.0
FWL_GV_E3_2: &fwl_gv_e32 !ref fwl_gv_nansen
with the constructor of the !ref
object resolving the scalar fwl_gv_nansen
, with some application specific code. Normally the anchor and alias events are resolved by the composer loader step before composing (and if so that information is no longer available).
来源:https://stackoverflow.com/questions/56564835/combining-anchor-and-alias-in-one-line-in-triggers-parsererror-expected-block