Specifying styles for portions of a PyYAML dump

送分小仙女□ 提交于 2019-11-29 13:50:56

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!