Last active
June 19, 2023 16:08
-
-
Save paulkernstock/6df1c7ad37fd71b1da3cb05e70b9f522 to your computer and use it in GitHub Desktop.
Literal block scalars with PyYAML's dump
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import yaml | |
from yaml.representer import SafeRepresenter | |
class LiteralString(str): | |
pass | |
def change_style(style, representer): | |
def new_representer(dumper, data): | |
scalar = representer(dumper, data) | |
scalar.style = style | |
return scalar | |
return new_representer | |
represent_literal_str = change_style('|', SafeRepresenter.represent_str) | |
yaml.add_representer(LiteralString, represent_literal_str) | |
markdown = """ | |
# Markdown Document | |
Foo Bar Baz | |
""" | |
data = {'string': LiteralString(markdown)} | |
print(yaml.safe_dump(data)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment