nnutter
nnutter

Reputation: 1844

Is there a way to dump YAML in same version it was loaded in with ruamel.yaml?

Is there a good way with ruamel.yaml to dump a YAML file back out in the same version as it is loaded in? If I have a %YAML 1.1 directive in the file I would like to be able to dump the file back out in YAML 1.1 without having to hard-code version='1.1'.

So given some data like,

%YAML 1.1
---
is_string: 'on'
is_boolean: on

I would like to avoid hard-coding version='1.1' on the round_trip_dump(),

x = f.read()
d = round_trip_load(x)
round_trip_dump(d, f, explicit_start=True)

Upvotes: 0

Views: 326

Answers (1)

Anthon
Anthon

Reputation: 76578

The version of the YAML file is a fleeting value, which gets reset after loading. It was (is) my plan to make the version of the latest document loaded available somehow, but with multiple documents in a stream this needs some more thought.

For single document streams you can do the following to capture the version from the directive. This is all done with the new API. With the old API that you are using in the example the same is possible, but more difficult because there is no YAML() instance to attach attributes to:

import sys
from ruamel.yaml import YAML
from ruamel.yaml.parser import Parser

yaml_str = """\
%YAML 1.1
---
is_string: 'on'
is_boolean: on
"""

class MyParser(Parser):
    def dispose(self):
        self.loader.last_yaml_version = self.yaml_version
        Parser.dispose(self)


yaml = YAML()
yaml.Parser = MyParser
data = yaml.load(yaml_str)

yaml2 = YAML()
yaml2.version = yaml.last_yaml_version
yaml2.dump(data, sys.stdout)

which gives:

%YAML 1.1
---
is_string: 'on'
is_boolean: true

Please note that it is necessary to create a clean, new object for output, as the "unversioned" reading doesn't fully reset the yaml instance, when encountering the %YAML 1.1 directive.

It is also possible to dump the value associated with is_boolean as on, but that would affect all booleans in the stream.

Upvotes: 1

Related Questions