anytree icon indicating copy to clipboard operation
anytree copied to clipboard

An enhance way added into DictImporter for supporting different nodeClass.

Open yiyunzhi opened this issue 1 year ago • 1 comments

An enhance way added into DictImporter for supporting different nodeClass. Sometimes I need import the tree back, which has different nodeClass. I found below workround. please consider it, if possible implemented as new feature.

class ExAnyTreeDictImporter(DictImporter):
    def __init__(self, node_cls, node_cls_map: dict = {}):
        DictImporter.__init__(self, nodecls=node_cls)
        self.nodeClsMap = node_cls_map

    def import_(self, data):
        """Import tree from `data`."""
        return self.__ex_import(data)

    def __ex_import(self, data: dict, parent=None):
        assert isinstance(data, dict)
        assert "parent" not in data
        _attrs = dict(data)
        _children = _attrs.pop("children", [])
        if '_klass_' in _attrs:
            _cls = self.nodeClsMap.get(_attrs.pop('_klass_'), self.nodecls)
        else:
            _cls = self.nodecls
        _node = _cls(parent=parent, **_attrs)
        for child in _children:
            self.__ex_import(child, parent=_node)
        return _node

yiyunzhi avatar Nov 01 '23 21:11 yiyunzhi

I like the idea. Will try to integrate it.

c0fec0de avatar Nov 06 '23 06:11 c0fec0de