Skip to content
Advertisement

A single string in single quotes with PyYAML

When I edit a YAML file in Python with PyYAML, all of my string values are saved back to the original file without quotes.

JavaScript

I wanted one of those strings to be surrounded with single quotes:

JavaScript

Changing the default_style parameter in yaml_dump affects whole file, which is not desired. I thought about adding single quotes to the beginning and end of a string that I want to be surrounded with:

JavaScript

However, this ends up with a dumped YAML looking like this:

JavaScript

I have tried escaping the single quote in various ways, using unicode or raw strings, all to no avail. How can I make only one of my YAML values to be a string surrounded with single quotes?

Advertisement

Answer

You can graft such functionality onto PyYAML but it is not easy. The value in the mapping for three has to be some instance of a class different from a normal string, otherwise the YAML dumper doesn’t know that it has to do something special and that instance is dumped as string with quotes. On loading scalars with single quotes need to be created as instances of this class. And apart from that you probably don’t want the keys of your dict/mapping scrambled as PyYAML does by default.

I do something similar to the above in my PyYAML derivative ruamel.yaml for block style scalars:

JavaScript

doesn’t throw an assertion error.


To start with the dumper, you can “convert” the valueThree string:

JavaScript

but this cannot be dumped, as the dumper doesn’t know about the SingleQuotedScalarString. You can solve that in different ways, the following extends ruamel.yaml‘s RoundTripRepresenter class:

JavaScript

Once again doesn’t throw an error. The above can be done in PyYAML and the safe_load/safe_dump in principle, but you would need to write code to preserve the key ordering, as well as some of the base functionality. (Apart from that PyYAML only supports the older YAML 1.1 standard not the YAML 1.2 standard from 2009).

To get the loading to work without using the explicit data['three'] = SingleQuotedScalarString(data['three']) conversion, you can add the following before the call to ruamel.yaml.round_trip_load():

JavaScript

There are different ways to do the above, including subclassing the RoundTripConstructor class, but the actual method to change is small and can easily be patched.


Combining all of the above and cleaning up a bit you get:

JavaScript

Which still runs without assertion error, i.e. with dump output equalling input. As indicated you can do this in PyYAML, but it requires considerably more coding.


With a more modern version (ruamel.yaml>0.14) you can do:

JavaScript

and preserve the single quotes.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement