Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

An enhance way added into DictImporter for supporting different nodeClass. #245

Open
yiyunzhi opened this issue Nov 1, 2023 · 1 comment

Comments

@yiyunzhi
Copy link

yiyunzhi commented Nov 1, 2023

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
@c0fec0de
Copy link
Owner

c0fec0de commented Nov 6, 2023

I like the idea. Will try to integrate it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants