5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PyYamlの出力時にreferenceの機能を無効にする方法

Posted at

何も設定せずにyaml.dumpするとreferenceの機能が使われてしまう。不要な場合もある。

import yaml


person = {
    "name": "foo",
    "age": 20
}
d = [person, person]

print(yaml.dump(d))

例えば以下のような出力になる。

- &id001 {age: 20, name: foo}
- *id001

yaml.dumpにDumperオプションが渡せる。そしてここで渡すDumperクラスのignore_aliases()メソッドをTrueを返すようにしてあげれば良い。

class IgnoreReferenceDumper(yaml.Dumper):
    def ignore_aliases(self, data):
        return True

print(yaml.dump(d, Dumper=IgnoreReferenceDumper))

平和が訪れた。

- {age: 20, name: foo}
- {age: 20, name: foo}
5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?