File size: 1,524 Bytes
ab4488b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# -*- coding: utf-8 -*-
from anytree import AnyNode
from ..config import ASSERTIONS
class DictImporter:
"""
Import Tree from dictionary.
Every dictionary is converted to an instance of `nodecls`.
The dictionaries listed in the children attribute are converted
likewise and added as children.
Keyword Args:
nodecls: class used for nodes.
>>> from anytree.importer import DictImporter
>>> from anytree import RenderTree
>>> importer = DictImporter()
>>> data = {
... 'a': 'root',
... 'children': [{'a': 'sub0',
... 'children': [{'a': 'sub0A', 'b': 'foo'}, {'a': 'sub0B'}]},
... {'a': 'sub1'}]}
>>> root = importer.import_(data)
>>> print(RenderTree(root))
AnyNode(a='root')
βββ AnyNode(a='sub0')
β βββ AnyNode(a='sub0A', b='foo')
β βββ AnyNode(a='sub0B')
βββ AnyNode(a='sub1')
"""
def __init__(self, nodecls=AnyNode):
self.nodecls = nodecls
def import_(self, data):
"""Import tree from `data`."""
return self.__import(data)
def __import(self, data, parent=None):
if ASSERTIONS: # pragma: no branch
assert isinstance(data, dict)
assert "parent" not in data
attrs = dict(data)
children = attrs.pop("children", [])
node = self.nodecls(parent=parent, **attrs)
for child in children:
self.__import(child, parent=node)
return node
|