ruamel yaml disabling alias for dumping

First of all, I don’t think the output you present is complete, as it is invalid YAML and I certainly hope ruamel.yaml did not generate that as shown (if it did file a bug report with the complete source).


I don’t know where you got that example from but the method ignore_aliases() is called with a data structure and should return True if any aliases should be ignored. It is not something you call yourself. You can subclass the Representer or monkey-patch that on the RoundTripRepresenter.

The method in representer.py should take a data parameter and always return False:

import sys
from pathlib import Path
import ruamel.yaml

# your output minus the `- *id002` alias that has no corresponding anchor
in_file = Path('Test.yaml')  

# monkey patch:
ruamel.yaml.representer.RoundTripRepresenter.ignore_aliases = lambda x, y: True

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
data = yaml.load(in_file)

yaml.dump(data, sys.stdout)

which gives:

templates:
  - name: freedom
    users:
      - name: service-account2
        permissions:
          - browse
          - read
  - name: liberty
    users:
      - name: service-account2
        permissions:
          - browse
          - read
      - name: service-account3
        permissions:
          - browse
          - read
      - name: service-account4
        permissions:
          - browse
          - read

Alternatively you can do the somewhat more verbose:

import sys
from pathlib import Path
import ruamel.yaml

# your output minus the `- *id002` alias that has no corresponding anchor
in_file = Path('Test.yaml')  

class NonAliasingRTRepresenter(ruamel.yaml.representer.RoundTripRepresenter):
    def ignore_aliases(self, data):
        return True


yaml = ruamel.yaml.YAML()
yaml.Representer = NonAliasingRTRepresenter
yaml.indent(mapping=2, sequence=4, offset=2)
data = yaml.load(in_file)

yaml.dump(data, sys.stdout)

which gives the same output.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top