58

I know there are a few questions about this on StackOverflow, but I couldn't find what I was looking for.

I'm using pyyaml to read (.load()) a .yml file, modify or add a key, and then write it (.dump()) again. The problem is that I want to keep the file format post-dump, but it changes.

For example, I edit the key en.test.index.few to say "Bye" instead of "Hello".

Python:

with open(path, "r", encoding = "utf-8") as yaml_file:
    self.dict = yaml.load(yaml_file)

Then, after changing the key:

with open(path, "w", encoding = "utf-8") as yaml_file:
    dump = pyyaml.dump(self.dict, default_flow_style = False, allow_unicode = True, encoding = None)
    yaml_file.write( dump )

Yaml:

Before:

en:
  test:
    new: "Bye"
    index:
      few: "Hello"
  anothertest: "Something"

After:

en:
  anothertest: Something
  test:
    index:
      few: Hello
    new: Bye

Is there a way to keep the same format? For example the qoutes and order. Am I using the wrong tool for this?

I know maybe the original file it's not entirely correct, but I have no control over it (it's a Ruby-on-Rails i18n file).

Thank you very much.

evandrix
  • 6,041
  • 4
  • 27
  • 38
nicosantangelo
  • 13,216
  • 3
  • 33
  • 47
  • 8
    `yaml.dump` has a `default_style` argument. Using `default_style='"'` will keep your string values in double quotes, but your keys and any other value types will also be wrapped in double quotes. – dirn Dec 27 '13 at 20:13
  • 1
    Thanks!, I'll keep it in mind, it would have been really useful if it wasn't for the keys :( – nicosantangelo Dec 27 '13 at 23:15
  • You'll probably have a hard time ordering the keys, too. `yaml.load` gives you a `dict`; its keys are unordered. `yaml.dump` probably outputs in whatever order the iteration goes. – dirn Dec 28 '13 at 01:57
  • 1
    The new file represents exactly the same information (in YAML) as the origin file; there is no reason to keep the same format. –  Feb 19 '14 at 12:37
  • @Evert that's true, but I wanted to keep the format because it's useful given the context of the sublime package I have created https://github.com/NicoSantangelo/sublime-text-i18n-rails – nicosantangelo Feb 20 '14 at 18:57
  • It's possible to maintain the ordering of the keys now, using the `sort_keys=False` parameter in `yaml.dump()` – aspiring1 Jun 10 '21 at 06:59

3 Answers3

110

Below, ruamel.yaml is used instead.

ruamel.yaml is actively maintained. Unlike PyYAML, ruamel.yaml supports:

  • YAML <= 1.2. PyYAML only supports YAML <= 1.1. This is vital, as YAML 1.2 intentionally breaks backward compatibility with YAML 1.1 in several edge cases. This would usually be a bad thing. In this case, this renders YAML 1.2 a strict superset of JSON. Since YAML 1.1 is not a strict superset of JSON, this is a good thing.
  • Roundtrip preservation. When calling yaml.dump() to dump a dictionary loaded by a prior call to yaml.load():
    • PyYAML naively ignores all input formatting – including comments, ordering, quoting, and whitespace. Discarded like so much digital refuse into the nearest available bit bucket.
    • ruamel.yaml cleverly respects all input formatting. Everything. The whole stylistic enchilada. The entire literary shebang. All.

Library Migration

Switching from PyYAML to ruamel.yaml in existing applications is typically as simple as changing the library import to:

from ruamel import yaml

This works because ruamel.yaml is a PyYAML fork that conforms to the PyYAML API.

No other changes should be needed. The yaml.load() and yaml.dump() functions should continue to behave as expected.

Roundtrip Preservation and What It Can Do for You

For backward compatibility with PyYaml, the yaml.load() and yaml.dump() functions do not perform roundtrip preservation by default. To do so, explicitly pass:

  • The optional Loader=ruamel.yaml.RoundTripLoader keyword parameter to yaml.load().
  • The optional Dumper=ruamel.yaml.RoundTripDumper keyword parameter to yaml.dump().

An example kindly "borrowed" from ruamel.yaml documentation:

import ruamel.yaml

inp = """\
# example
name:
  # Yet another Great Duke of Hell. He's not so bad, really.
  family: TheMighty
  given: Ashtaroth
"""

code = ruamel.yaml.load(inp, Loader=ruamel.yaml.RoundTripLoader)
code['name']['given'] = 'Astarte'  # Oh no you didn't.

print(ruamel.yaml.dump(code, Dumper=ruamel.yaml.RoundTripDumper), end='')

It is done. Comments, ordering, quoting, and whitespace will now be preserved intact.

bschlueter
  • 3,817
  • 1
  • 30
  • 48
Cecil Curry
  • 9,789
  • 5
  • 38
  • 52
  • 4
    I must say this is a wonderful answer. I'm currently not developing the project that used PyYAML but I'll definitely give `ruamel.yaml` a try when I have some spare time and accept the answer if it works. Thanks! – nicosantangelo May 07 '16 at 23:24
  • It actually doesn't maintain all formatting. For instance, quotes are not kept. – sjmh Jun 08 '16 at 08:27
  • @sjmh If `ruamel.yaml` fails to roundtrip preserve _any_ formatting (including but not limited to quote style), **that's a bug.** Consider submitting an issue at `ruamel.yaml`'s [issue tracker](https://bitbucket.org/ruamel/yaml/issues?status=new&status=open). The [principal maintainer](https://bitbucket.org/ruamel/) of `ruamel.yaml` is quite receptive and friendly, thankfully. Cheers! – Cecil Curry Jun 15 '16 at 03:09
  • 3
    @sjmh Starting with ruamel.yaml 0.11.12 you can specify `preserve_quotes=True` during loading, which will wrap the strings loaded with information needed for dumping. Also see [this answer](http://stackoverflow.com/a/38582476/1307905) – Anthon Aug 01 '16 at 09:55
  • @Anthon Will it somehow preserve blank lines between data? – Alex Harvey Aug 29 '16 at 00:55
  • @AlexHarvey Yes it will. Empty lines are considered comments without `#` and are preserved. But in case you'll be inserting new values, beware that the comments/empty lines are currently attached to mapping-keys/sequence-elements **before** the comment (i.e. comment gathering is greedy), even though visually the might be "closer" to the following key/element – Anthon Aug 29 '16 at 06:32
  • That's great to hear. I have a bunch of issues and I'll raise them in Bitbucket. Your project is fantastic, it's almost unbelievable no one has thought of it before! – Alex Harvey Aug 29 '16 at 09:05
  • Is this comment still up to date with [the current state of PyYAML?](https://github.com/yaml/pyyaml) – AlexLordThorsen Apr 23 '18 at 21:32
  • 50
    PyYAML has new maintainers now, and had a v4.1 release recently. The answer is outdated and silly content such as "PyYAML is a fetid corpse rotting.." should probably be edited out. – wim Jul 19 '18 at 04:53
  • 2
    @wim aaaand PyYAML development grinded to a halt again, with no meaningful changes since 5 months. The 4.1 release [broke](https://github.com/TankerHQ/tsrc/commit/f7fb55a5c540856560106b9e13ce3a6c347979a5) [many](https://github.com/heilaaks/snippy/commit/d81e82e1113daca6575f4e891397e480e69d6249) [projects](https://github.com/fecgov/openFEC/issues/3280), and we are currently sitting on 4.2b4, which is pretty embarrassing. There is little hope that it ever gets a proper release and lots of regret for not choosing ruamel in the first place. – Arne Nov 09 '18 at 12:30
  • 10
    3.x to 4.x is a major version number bump, so backwards incompat changes should be expected. I'm not denying PyYAML maintainership has problems and politics, but the language used in this answer is a bit excessive. It reads like an advertisement for ruamel.yaml or propaganda. – wim Nov 09 '18 at 15:04
  • 3
    Still dead. Never trust one release, only a pattern of releases. Long live ruamel.yaml – Alex H. Dec 05 '18 at 21:02
  • 2
    I am afraid the "new" PyYAML is very lacking from the point of view of usability in a Python environment. Some "maintainers" are tinkering around while they admittedly "learn Python". And they fight fiercely against obvious requests like preserving dictionary order just like Python does. It is a pity for such a relevant project. – gatopeich Apr 10 '19 at 09:30
  • while ruamel works better, its also faulty. The state of yaml loading + dumping in python is unfortunately quite bad. – lifeofguenter Oct 02 '19 at 11:34
  • 1
    ruamel.yaml is significantlly slower than pyyaml. Something to keep in mind – Dan Niero Oct 08 '19 at 08:05
  • 8
    This answer should be corrected. It immediately starts with false statements. Maybe they where true at the time it was written, but it is not longer the case. PyYaml is not dead and the web site is up. At the moment of writing this comment, PyYaml appear quite alive and kicking. Look at the latest releases: - 2019-07-30: PyYAML 5.1.2 is released. - 2018-06-06: PyYAML 5.1.1 is released. - 2019-03-13: LibYAML 0.2.2 and PyYAML 5.1 are released. - 2018-07-05: PyYAML 3.13 is released. - 2018-06-24: LibYAML 0.2.1 is released. This answer is misleading. – Dan Niero Oct 08 '19 at 08:13
  • 1
    The PyYAML source code can now be found at https://github.com/yaml/pyyaml , and shows quite some activity (in commits, issues & responses, and pull requests & merges). Perhaps these are all bad, but PyYAML is currently not unmaintained and dead. – 9769953 Feb 06 '20 at 12:28
  • While PyYAML is maintained and works well, the other library advertised here is questionable at best. The link is not even valid anymore, the project migrated from bitbucket to sourceforge and has very little activity over there. – scravy Jan 26 '21 at 21:47
  • I only edited it to remove language that was not appropriate for the SO. Some of it showed terrible lack of understanding of history. I can't endorse the library, or the recommendations in this post. – Rob Feb 22 '21 at 06:00
  • FWIW, PyYAML managed to convert our Git commit 45433e8 into 4543300000000 and broke our CI. The respective PR https://github.com/yaml/pyyaml/pull/174 is stalled since 2018. https://www.openhub.net/p/_compare?project_0=ruamel-yaml&project_1=PyYAML gave us enough confidence to make the switch to ruamel.yaml. – Torsten Bronger Sep 18 '21 at 05:59
6

In my case, I want " if value contains a { or a }, otherwise nothing. For example:

 en:
   key1: value is 1
   key2: 'value is {1}'

To perform that, copy function represent_str() from file representer.py in module PyYaml and use another style if string contains { or a }:

def represent_str(self, data):
    tag = None
    style = None
    # Add these two lines:
    if '{' in data or '}' in data:
        style = '"'
    try:
        data = unicode(data, 'ascii')
        tag = u'tag:yaml.org,2002:str'
    except UnicodeDecodeError:
        try:
            data = unicode(data, 'utf-8')
            tag = u'tag:yaml.org,2002:str'
        except UnicodeDecodeError:
            data = data.encode('base64')
            tag = u'tag:yaml.org,2002:binary'
            style = '|'
    return self.represent_scalar(tag, data, style=style)

To use it in your code:

import yaml

def represent_str(self, data):
  ...

yaml.add_representer(str, represent_str)

In this case, no diffences between keys and values and that's enough for me. If you want a different style for keys and values, perform the same thing with function represent_mapping

Nelson G.
  • 5,145
  • 4
  • 43
  • 54
2

First

To represent dictionary data is used following code:

mapping = list(mapping.items())
    try:
        mapping = sorted(mapping)
    except TypeError:
        pass

It is why ordering is changed

Second

Information about how scalar type was presented (with double quote or not) is lost when reading (this is principal approach of library)

Summary

You can create own class based on 'Dumper' and to overload method 'represent_mapping' for changing behaviour how dictionary will be presented

For saving information about double quotes for scalar you must also create own class based on 'Loader', but i am afraid that it will affect and other classes and will doing it difficult

Habibutsu
  • 592
  • 1
  • 8
  • 20