roundtrip loses anchors on scalars

Issue #166 duplicate
Min RK
created an issue

Roundtrip loses anchors on scalars. Anchors on dicts appear to roundtrip without issue, but anchors on scalars appear to be resolved at load time and discarded, resulting in the dereferenced value being written instead of anchors and references.

Test case showing that dict anchors work while scalar anchors don't:

import sys
import ruamel.yaml
print(ruamel.yaml.__version__)

yaml = ruamel.yaml.YAML(typ='rt')

tests = [
"""
first: &anchor value
second: *anchor
""",
"""
first: &anchor
  key: value
second: *anchor
"""
]

for test in tests:
    data = yaml.load(test)
    print("\nExpecting: %s" % test)
    print("Got: ")
    yaml.dump(data, sys.stdout)

Output with ruamel.yaml-0.15.34:

0.15.34

Expecting:
first: &anchor value
second: *anchor

Got:
first: value
second: value

Expecting:
first: &anchor
  key: value
second: *anchor

Got:
first: &anchor
  key: value
second: *anchor

Comments (2)

  1. Ruamel/Anthon van der Neut repo owner

    This is not by design, but a result of the scalars being mapped directly to Python primitives. That this works for mapping/dict and sequence/list is because in round-trip-mode, you don't get a dict resp. list, you get a subclass that can keep the tag information.

    Although the string values are subclassed (when using preserve_quotes, IIRC I don't keep tag information on those) and neither do I do so for integers, floats, dates etc.

    In principle this is possible, even by subclassing the RoundTripConstructor, but it is quite a bit of work and testing. The only real problem I see is with null, because (if I am not mistaken) you cannot subclass Python's None.

  2. Log in to comment