YAML を使用して Python オブジェクトの階層をダンプできます。
import yaml
class C():
def __init__(self, x, y):
self.x = x
self.y = y
class D():
def __init__(self, c, d):
self.c = c
self.d = d
d = D(c=C(x=1, y='hi'),
d='bye')
print yaml.dump(d)
出力を生成します:
!!python/object:__main__.D
c: !!python/object:__main__.C {x: 1, y: hi}
d: bye
しかし、いくつかの属性を選択的に非表示にしたいと考えています。したがってattribs_to_dump(obj)
、任意のオブジェクトに対して、ダンプしたい属性名のリストを返す関数があるとします。たとえば、次のようになります。
def attribs_to_dump(obj):
if obj.__class__ == C: return ['x']
if obj.__class__ == D: return ['c']
私の質問は、次の出力を得るためにどのようにフックattribs_to_dump
するのですか?yaml.dump
!!python/object:__main__.D
c: !!python/object:__main__.C {x: 1}
複雑な要因があります。オブジェクト階層を自分で前処理するのではなく、Yaml がオブジェクト階層をクロールするときに Yaml にフックすることで、効果を達成したいと考えています。その理由は、私が使用しているいくつかのライブラリに存在する魔法のために、階層内のすべてのオブジェクトが簡単に内省できるわけではないためですsetattr/getattr/__dict__
:-(...
すべての助けに感謝します!