日々精進

新しく学んだことを書き留めていきます

yamlを出力したときにインデントが足りないところがある

dictに配列をネストさせたオブジェクトをyamlに出力すると以下のようになる。

dictionary:
- A
- B

こうなってほしい。

dictionary:
  - A
  - B

こうするためには、以下のようにする。

    class FixIndentDumper(yaml.Dumper):
        def increase_indent(self, flow=False, indentless=False):
            return super(FixIndentDumper, self).increase_indent(flow, False)

    def _to_yaml(d: dict):
        yaml.dump(d, default_flow_style=False, Dumper=FixIndentDumper)

参考:

stackoverflow.com