The Python Oracle

Different YAML array representations

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping

--

Chapters
00:00 Different Yaml Array Representations
00:48 Accepted Answer Score 4
01:48 Answer 2 Score 5
02:49 Thank you

--

Full question
https://stackoverflow.com/questions/3144...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #ruby #yaml #pyyaml

#avk47



ANSWER 1

Score 5


As Jordan already pointed out the node style is a serialization detail. And the output is equivalent to your input.

With PyYAML you can get the same block style output by using the default_flow_style keyword when dumping:

yaml.dump(yaml.load("""\
key:
- value1
- value2
- value3
"""), sys.stdout, default_flow_style=False)

gives you:

key:
- value1
- value2
- value3

If you would be using the round-trip capabilities from ruamel.yaml (disclaimer: I am the author of that package) you could do:

import sys
import ruamel.yaml as yaml

yaml_str = """\
key:
- value1
- value2  # this is the second value
- value3
"""

data = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)

yaml.dump(data, sys.stdout, Dumper=yaml.RoundTripDumper, default_flow_style=False)

to get:

key:
- value1
- value2  # this is the second value
- value3

Not only does it preserve the flow/block style, but also the comment and the key ordering and some more transparently. This makes comparison (e.g. when using some revision control system to check in the YAML file), much easier.

For the service reading the YAML file this all makes no difference, but for the ease of checking whether you are transforming things correctly, it does.




ACCEPTED ANSWER

Score 4


Yes, to any YAML parser that follows the spec, they are equivalent. You can read the spec here: http://www.yaml.org/spec/1.2/spec.html

Section 3.2.3.1 is particularly relevant (emphasis mine):

3.2.3.1. Node Styles

Each node is presented in some style, depending on its kind. The node style is a presentation detail and is not reflected in the serialization tree or representation graph. There are two groups of styles. Block styles use indentation to denote structure; In contrast, flow styles styles rely on explicit indicators.

To clarify, a node is any structure in YAML, including arrays (called sequences in the spec). The single-line style is called a flow sequence (see section 7.4.1) and the multi-line style is called a block sequence (section 8.2.1). A compliant parser will deserialize both into identical objects.