Fallacy11
Fallacy11

Reputation: 610

How can I get pyyaml to correctly display structure in output?

Instead of getting normal line breaks like I'd expect it's just printing '\n'. How can I make the line break actually happen?

>>> test2 = [{'A':['a', 'b']}, {'B':'b'}]
>>> yaml.dump(test2)
'- A: [a, b]\n- {B: b}\n'
>>>

Upvotes: 3

Views: 1148

Answers (2)

Anthon
Anthon

Reputation: 76882

The dump() routines in PyYAML have several optional arguments, the first of which being the stream the data will be serialized to ( stream= ).

If you don't specify this stream a file like object will be created (StringIO() or BytesIO()) to which the data is serialized and in that case the the dump() routine returns that objects getvalue(), where it normally just returns None.

As you don't specify an output stream, PyYAML doesn't know where to write the output and returns the result of getvalue() in your case as string. If you would have provided the encoding= parameter you would get a bytes array on Python 3 and not a string.

You can of course print that string, but that is one of the most common mistakes I see people using PyYAML make. For a small datastructure this is excusable, but for large data structures creating a string representation in memory can consume large amounts of memory unnecessarily.

You should get used to the habit of providing the stream parameter:

>>> import yaml
>>> test2 = [{'A':['a', 'b']}, {'B':'b'}]
>>> yaml.dump(test2)
'- A: [a, b]\n- {B: b}\n'
>>> import sys
>>> yaml.dump(test2, stream=sys.stdout)
- A: [a, b]
- {B: b}
>>> 

This also prevents you from getting a double newline at the end of the output (one from the serialisation, and one from print).

Upvotes: 2

Luke Taylor
Luke Taylor

Reputation: 9600

You can get the line breaks to render using print. Strings displayed in the interactive prompt in this manner never render line breaks. You can tell how your string is displaying by the quotation marks (') displayed around the string, these won't appear with print.

>>> test2 = [{'A':['a', 'b']}, {'B':'b'}]
>>> yaml.dump(test2)
'- A: [a, b]\n- {B: b}\n'
>>> print(yaml.dump(test2))
- A: [a, b]
- {B: b}

>>> 

Upvotes: 1

Related Questions