Last active
January 23, 2018 19:20
-
-
Save alertedsnake/c521bc485b3805aa3839aef29e39f376 to your computer and use it in GitHub Desktop.
How to handle multi-line blocks nicely in yaml
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
from ruamel.yaml import YAML | |
def str_representer(dumper, data): | |
if len(data.splitlines()) > 1: # check for multiline string | |
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') | |
return dumper.represent_scalar('tag:yaml.org,2002:str', data) | |
def main(): | |
yaml = YAML() | |
yaml.default_flow_style = False | |
yaml.indent(sequence=4, offset=2) | |
yaml.representer.add_representer(str, str_representer) | |
data = { | |
"comment": """Jabberwocky, by Lewis Carroll | |
'Twas brillig, and the slithy toves | |
Did gyre and gimble in the wabe: | |
All mimsy were the borogoves, | |
And the mome raths outgrabe. | |
"Beware the jabberwock, my son! | |
The jaws that bite, the claws that catch! | |
Beware the Jubjub bird, and shun | |
The frumious Bandersnatch!" | |
He took his vorpal sword in hand: | |
Long time the manxome foe he sought -- | |
So rested he by the Tumtum tree, | |
And stood awhile in thought. | |
And, as in uffish thought he stood, | |
The Jabberwock, with eyes of flame, | |
Came whiffling through the tulgey wood, | |
And burbled as it came! | |
One, two! One, two! And through and through | |
The vorpal blade went snicker-snack! | |
He left it dead, and with its head | |
He went galumphing back. | |
"And hast thou slain the Jabberwock? | |
Come to my arms, my beamish boy! | |
O frabjous day! Callooh! Callay!" | |
He chortled in his joy. | |
'Twas brillig, and the slithy toves | |
Did gyre and gimble in the wabe: | |
All mimsy were the borogoves, | |
And the mome raths outgrabe. | |
""" | |
} | |
with open("test.yaml", 'w') as f: | |
yaml.dump(data, f) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment