Created
July 24, 2024 15:15
-
-
Save p-i-/0e7a27179569e07e5db35a30d36ec405 to your computer and use it in GitHub Desktop.
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 io import StringIO | |
from ruamel.yaml import YAML # pip install ruamel.yaml | |
def my_string_representer(dumper, data): | |
# '' generates `my_multiline: |-` and works perfectly | |
# '\n' generates `my_multiline: |` but load(save(J)) != J due to trailing | |
FIX = '' | |
is_multiline = '\n' in data | |
return dumper.represent_scalar( | |
'tag:yaml.org,2002:str', | |
data.strip() + FIX if is_multiline else data, | |
style='|' if is_multiline else None | |
) | |
# Initialize YAML object | |
yaml = YAML() | |
yaml.indent(mapping=2, sequence=4, offset=2) | |
yaml.default_flow_style = False | |
# Register the custom representer | |
yaml.Representer.add_representer(str, my_string_representer) | |
def load(filename): | |
with open(filename) as f: | |
return yaml.load(f) | |
def save(filename, data): | |
with open(filename, 'w') as f: | |
yaml.dump(data, f) | |
def stringify(data): | |
ss = StringIO() | |
yaml.dump(data, ss) | |
return ss.getvalue() | |
if __name__ == '__main__': | |
from textwrap import dedent | |
J = { | |
'foo': { | |
'i': 42, | |
'bar': { | |
'baz': dedent(''' | |
multiline stuff | |
here | |
and here | |
''').strip() | |
}, | |
'qux': "single line stuff" | |
}, | |
'fizz': 'buzz' | |
} | |
save('/tmp/test.yaml', J) | |
J2 = load('/tmp/test.yaml') | |
# print(stringify(J)) | |
# print(stringify(J2)) | |
# print(f"-{J['foo']['bar']['baz']}-") | |
# print(f"-{J2['foo']['bar']['baz']}-") | |
J = {'shape': 'a a', 'colours': '#0=97 #2=37 #5=16'} | |
print(stringify(J)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment