pythonyamlruamel.yaml

ruamel.yaml always dumps YAML end marker ("...") even if yaml.explicit_end=False


I am wondering if this is a bug or intentional, but anyway.

Why does dumping a single value with ruamel.yaml always include an explicit YAML end marker?

import sys
from ruamel.yaml import YAML
yaml=YAML()
yaml.explicit_end=False
yaml.dump(1, sys.stdout)

Produces

1
...

Can the be easily skipped somehow?


Solution

  • The reason the document-end-marker (...) is added is because the number is dumped as a plain scalar at the root level of the document. The same happens if you dump a string (assuming that string can be dumped without quotes without being misinterpreted, i.e. string consisting of numbers only have to be quoted in order not to be seen as an integer).

    Without document-end-marker, on loading from a stream, the parser would not know if the document is complete, or the stream just waiting to filled. The document-end-marker takes away this ambiguity, so this is intentional, but e.g. when parsing a file (instead of generic stream), that can, and will, also be done by checking for end-of-file.

    There are several ways around this, one is to transform the output:

    import sys
    import ruamel.yaml
    
    def strip_document_end_marker(s):
       if s.endswith('...\n'):
           return s[:-4]
    
    yaml = ruamel.yaml.YAML()
    yaml.dump("abc", sys.stdout, transform=strip_document_end_marker)
    

    which gives:

    abc
    

    The above should also work with dump_all for multiple documents (and the last one being a root level plain scalar).

    Another way to achieve this is to reset the open_ended attribute after writing a plain value:

    import sys
    import ruamel.yaml
    
    yaml = ruamel.yaml.YAML()
    
    def wp(self, *args, **kw):
        self.write_plain_org(*args, **kw)
        self.open_ended = False
    
    yaml.Emitter.write_plain_org = yaml.Emitter.write_plain
    yaml.Emitter.write_plain = wp
    yaml.dump("abc", sys.stdout)
    

    which also gives:

    abc