Specifying styles for portions of a PyYAML dump

前端 未结 1 1196
天命终不由人
天命终不由人 2020-12-20 13:21

I\'m using YAML for a computer and human-editable and readable input format for a simulator. For human readability, some parts of the input are mostly amenable to block styl

相关标签:
1条回答
  • 2020-12-20 13:36

    It turns out this can be done by defining subclasses with representers for each item I want not to follow default_flow_style, and then converting everything necessary to those before dumping. In this case, that means I get 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)
    

    Annoyingly, the easier-to-use dumper.represent_list and dumper.represent_dict don't allow flow_style to be specified, so I have to specify the tag, but the system does work.

    0 讨论(0)
提交回复
热议问题