Skip to content

Instantly share code, notes, and snippets.

@retorquere
Created May 9, 2019 16:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save retorquere/c43b5394c5e45b4c5b54b46479725e3c to your computer and use it in GitHub Desktop.
Save retorquere/c43b5394c5e45b4c5b54b46479725e3c to your computer and use it in GitHub Desktop.
import yaml
from collections import OrderedDict
class quoted(str):
pass
def quoted_presenter(dumper, data):
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='"')
yaml.add_representer(quoted, quoted_presenter)
class literal(str):
pass
def literal_presenter(dumper, data):
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
yaml.add_representer(literal, literal_presenter)
def ordered_dict_presenter(dumper, data):
return dumper.represent_dict(data.items())
yaml.add_representer(OrderedDict, ordered_dict_presenter)
d = OrderedDict(short=quoted("Hello"), long=literal('<style \n xmlns="http://purl.org/net/xbiblio/csl"\n class="note"\n version="1.0">\n <info>\n <title>Test fixture</title>\n <id>http://citationstyles.org/tests/fixture</id>\n <link href="http://citationstyles.org/tests/fixture" rel="self"/>\n <link href="http://citationstyles.org/documentation/text" rel="documentation"/>\n <category citation-format="author-date"/>\n <updated>2014-04-30T13:19:38+00:00</updated>\n <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>\n </info>\n <macro name="author">\n <names variable="author">\n <name form="short" />\n </names>\n </macro>\n <citation>\n <sort>\n <key macro="author" />\n </sort>\n <layout delimiter="; ">\n <text macro="author" />\n </layout>\n </citation>\n</style>'))
print(yaml.dump(d))
@johnhaire89
Copy link

johnhaire89 commented Jun 18, 2021

I know this is very dead but I don't have enough rep on stackoverflow to answer your comment.
The reason this doesn't get quoted as a block literal is that PyYaml ignores the style="|" argument if your string contains adjacent newlines or whitespace before or after a newline. PyYaml dumps it as a double-quoted scalar instead.
yaml/pyyaml#121

@bileschi
Copy link

Thanks @johnhaire89 ! This would have taken a long time to figure out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment