构造具有非标准类型的节点

时间:2016-07-22 16:32:48

标签: python yaml

如果我可以导入yaml文件并使用我自己的对象类型进行映射和序列,我正在努力解决

在标准构造函数中,它使用内置类型: http://pyyaml.org/browser/pyyaml/tags/3.10/lib/yaml/constructor.py#L112 http://pyyaml.org/browser/pyyaml/tags/3.10/lib/yaml/constructor.py#L120

我想知道是否有办法用我自己的数据类型构建这些用于映射和序列而不用我猴子修补yaml.constructor.BaseConstructor.construct _ *

我尝试了以下内容:

from __future__ import absolute_import, unicode_literals
from noconflict import classmaker
from yaml import YAMLObject
import yaml

try:
    # Try for python 3 first
    from collections.abc import Sequence
    from collections.abc import Mapping
except ImportError:
    from collections import Sequence
    from collections import Mapping


class SettingsMapping(Mapping, YAMLObject):
    __metaclass__ = classmaker()
    yaml_tag = '!!map'

    def __init__(self, *args, **kwargs):
        self.__dict__.update(*args, **kwargs)

    def __getitem__(self, item, default=None):
        return self.__dict__.get(item, default=default)

    def __iter__(self):
        return self.__dict__.iterkeys()

    def __len__(self):
        return len(self.__dict__)


class SettingsSequence(Sequence, YAMLObject):
    __metaclass__ = classmaker()
    yaml_tag = '!!seq'

    def __init__(self, *args):
        self.list = args

    def __getitem__(self, item):
        return self.list[item]

    def __len__(self):
        return len(self.list)

for cls in [SettingsMapping, SettingsSequence]:
    yaml.add_constructor(cls.yaml_tag, cls)

y = yaml.load(open('input.yaml')

其中noconflict.classmaker来自: http://code.activestate.com/recipes/204197-solving-the-metaclass-conflict/

但:

>>> type(y)
dict

0 个答案:

没有答案