'CommentedMap' object has no attribute '_context_manager' during data dump with ruamel.yaml

Viewed 508

Here's my code:

import ruamel.yaml
import pathlib


class YamlLoader:

    @staticmethod
    def safe_load(filename):

        filepath = pathlib.Path(filename)

        with open(filepath) as stream:

            if ruamel.yaml.version_info < (0, 15):
                data = ruamel.yaml.safe_load(stream)
            else:
                yml = ruamel.yaml.YAML(typ='safe', pure=True)
                data = yml.load(stream)

        return data

    @staticmethod
    def save(yaml, filename):

        filepath = pathlib.Path(filename)

        if ruamel.yaml.version_info < (0, 15):
            ruamel.yaml.safe_dump(yaml, filepath)
        else:
            ruamel.yaml.YAML.dump(yaml, filepath)

my code in main.py:

data = YamlLoader.safe_load("data.yaml")
print(data)

I then get my YAML data in the variable.

However, when I then do:

YamlLoader.save(data, "output.yaml")

I get the error message:

Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.8/site-packages/ruamel/yaml/main.py", line 434, in dump if self._context_manager: AttributeError: 'CommentedMap' object has no attribute '_context_manager'

Most likely I'm using the API in a wrong way, but I can't figure out where the issue is.

1 Answers

The last line of your code has a problem:

ruamel.yaml.YAML.dump(yaml, filepath)

as you are not creating an instance of YAML like you do wnen loading.

Either do:

yml = ruamel.yaml.YAML()
yml.dump(yaml, filepath)

or do :

ruamel.yaml.YAML().dump(yaml, filepath)
Related