I’m encountering an issue with preserving YAML anchors for numeric value, particularly with the number 0 all the other numeric value works fine, when using ruamel.yaml
. Here’s what’s happening:
Context: I’m using ruamel.yaml
to parse and manipulate YAML files in Python. I need to keep anchors for numeric values intact, but here’s the problem:
from ruamel.yaml import YAML, ScalarInt, PlainScalarString
# Custom loader to attempt to preserve anchors for numeric values
class CustomLoader(YAML):
def __init__(self):
super().__init__(typ='rt')
self.preserve_quotes = True
self.explicit_start = True
self.default_flow_style = False
def construct_yaml_int(self, node):
value = super().construct_yaml_int(node)
if node.anchor:
# Preserve the anchor for numeric values
if value == 0:
return PlainScalarString("0", anchor=node.anchor.value)
else:
return ScalarInt(value, anchor=node.anchor.value)
return value
yaml = CustomLoader()
# Load the YAML file
with open('current.yaml', 'r') as current_file:
current_data = yaml.load(current_file)
print("Debug: current_data after load:", current_data)
for key, value in current_data.items():
print(f"Debug: Key '{key}', value type: {type(value)}, has anchor: {hasattr(value, 'anchor')}, anchor value: {getattr(value, 'anchor', None)}")
current.yaml
:
person: &person_age 0
person: &person_age 1 # this works
Expected Behavior: The anchor &person_age
should be preserved for the person key with the value 0.
Actual Behavior: The anchor is not preserved; hasattr(value, 'anchor')
returns False
, and the value type is <class 'int'>
rather than ScalarInt
or PlainScalarString
with an anchor.
What I’ve tried: I’ve tried to override construct_yaml_int
in a custom loader to manually preserve anchors for integers, but it doesn’t seem to work. I’ve ensured that ruamel.yaml
is configured with typ='rt'
for round-trip preservation. I’ve experimented with quoting the 0 in the YAML file (person: &person_age "0"
), which does preserve the anchor, but this isn’t a feasible solution for my use case where users might not quote their numeric values.
Question: How can I ensure that anchors are preserved for numeric value 0, when using ruamel.yaml
? Is there a way to force ruamel.yaml
to handle anchors for numbers without needing them to be quoted in the source YAML?
Any insights or alternative approaches would be greatly appreciated.
Version- [Python:3.12.5, ruamel.yaml:0.18.6]