question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Multiline strings are ugly after dumping

See original GitHub issue
>>> lines = """
... a
... b
... c
... """
>>> lines
'\na\nb\nc\n'
>>> print(yaml.dump({'a': lines}, default_flow_style=False))
a: '

  a

  b

  c

  '

>>> # although roundtrip of dump-load is correct
>>> yaml.load(yaml.dump({'a': lines}))
{'a': '\na\nb\nc\n'}

This could output much shorter

a: |
  a
  b
  c

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:22
  • Comments:12 (4 by maintainers)

github_iconTop GitHub Comments

12reactions
jgunstonecommented, Jan 21, 2022

found this on StackOverflow as a quick fix for my requirement:

parsed = {'fdir_root': '/mnt/c/engDev/git_mf/ipyrun/tests/examples/line_graph_batch',
 'fpth_config': '/mnt/c/engDev/git_mf/ipyrun/tests/examples/line_graph_batch/config-shell_handler.json',
 'title': '# Plot Straight Lines\n### example RunApp',
 'configs': []}

import yaml
def str_presenter(dumper, data):
    """configures yaml for dumping multiline strings
    Ref: https://stackoverflow.com/questions/8640959/how-can-i-control-what-scalar-form-pyyaml-uses-for-my-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)

yaml.add_representer(str, str_presenter)
yaml.representer.SafeRepresenter.add_representer(str, str_presenter) # to use with safe_dum

s = yaml.dump(parsed, indent=2)  # , sort_keys=True)
print(s)

>>> configs: []
>>> fdir_root: /mnt/c/engDev/git_mf/ipyrun/tests/examples/line_graph_batch
>>> fpth_config: /mnt/c/engDev/git_mf/ipyrun/tests/examples/line_graph_batch/config-shell_handler.json
>>> title: |-
>>>   # Plot Straight Lines
>>>   ### example RunApp
5reactions
cjw296commented, Apr 12, 2022

Slight tweak, better handles strings ending in a newline and might be a bit faster:

def str_presenter(dumper, data):
    """configures yaml for dumping multiline strings
    Ref: https://stackoverflow.com/questions/8640959/how-can-i-control-what-scalar-form-pyyaml-uses-for-my-data"""
    if data.count('\n') > 0:  # 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)
Read more comments on GitHub >

github_iconTop Results From Across the Web

ValueError compatibility and multi-line string aesthetics?
You can even make your own ValueError subclass that represents itself by dumping the long string. You can even throw the textwrap stuff...
Read more >
Multiline string literals: can we get rid of the need for ...
I.e. The rule would be that a single quote at the end of a line starts a multi-line string literal. The string is...
Read more >
my girlfriend is getting uglier and uglier to me by the day
I know the automatic response is 'dump her' but she's really fragile and 'sweet' she cries easily and I know how much I...
Read more >
Strings in YAML - To Quote or not to Quote | tinita [blogs.perl.org]
If you look at JSON, you have only one style to encode strings, and that's the double quoted style which doesn't allow literal...
Read more >
If an ex starts talking to girls, right after you break up ... - Quora
Why is it good not to get in a relationship right away after a long term break up? You replace your ex with...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found