Specifying Styles for PyYAML Dump Parts

I use YAML for a computer and a human-editable and readable input format for the simulator. For readability, some parts of the input are mostly suitable for a lock style, while a stream style is better for others.

By default, PyYAML uses a block style where there are nested maps or sequences, and a stream style throughout the world. * default_flow_style * allows you to select the all-stream or all-block-style style.

But I would like to output files from the form more

bonds: - { strength: 2.0 } - ... tiles: - { color: red, edges: [1, 0, 0, 1], stoic: 0.1} - ... args: block: 2 Gse: 9.4 

As you can see, this does not correspond to a consistent template for styles, but instead changes depending on the part of the file. Essentially, I would like to be able to indicate that all values ​​in some block style sequences will be in stream style. Is there any way to get such fine control over dumping? The ability to reset the top-level display in a specific order, without requiring that this order (e.g. omap) be enjoyable for readability.

+6
source share
1 answer

It turns out that this can be done by defining subclasses with views for each element that I want to not follow default_flow_style, and then transforming everything I need for them before resetting it. In this case, this means that I am getting something like:

 class blockseq( dict ): pass def blockseq_rep(dumper, data): return dumper.represent_mapping( u'tag:yaml.org,2002:map', data, flow_style=False ) class flowmap( dict ): pass def flowmap_rep(dumper, data): return dumper.represent_mapping( u'tag:yaml.org,2002:map', data, flow_style=True ) yaml.add_representer(blockseq, blockseq_rep) yaml.add_representer(flowmap, flowmap_rep) def dump( st ): st['tiles'] = [ flowmap(x) for x in st['tiles'] ] st['bonds'] = [ flowmap(x) for x in st['bonds'] ] if 'xgrowargs' in st.keys(): st['xgrowargs'] = blockseq(st['xgrowargs']) return yaml.dump(st) 

It is annoying that the easy-to-use dumper.represent_list and dumper.represent_dict do not allow flow_style to be specified, so I have to specify a tag, but the system works.

+11
source

All Articles