Debian Codegraph @

docs/tricks/multidim.rst

raw
1 Multidimensional Trees
2 ======================
3
4 **Application**: Tree nodes should be hooked-up in multiple trees.
5
6 An anytree node is only able to be part of **one** tree, not multiple.
7 The following example shows how to handle this.
8
9 **Example**: 4 objects `A`, `B`, `C` and `D` shall be part of the
10 trees `X` and `Y`.
11
12 The objects `A`, `B`, `C` and `D` are instances of a class `Item`.
13 It is *not* a tree node. It just contains references `x` and `y` to the node
14 representations in the corresponding trees.
15
16 >>> class Item:
17 ... def __init__(self, name):
18 ... self.name = name
19 ... self.x = None
20 ... self.y = None
21 ... def __repr__(self):
22 ... return "Item(%r)" % self.name
23 >>> a = Item('A')
24 >>> b = Item('B')
25 >>> c = Item('C')
26 >>> d = Item('D')
27
28 The tree nodes just contain the reference to `item` and take care of the
29 proper reference, by using the attach/detach protocol.
30
31 >>> from anytree import NodeMixin, RenderTree
32 >>> class NodeX(NodeMixin):
33 ... def __init__(self, item, parent=None):
34 ... self.item = item
35 ... self.parent = parent
36 ... def _pre_detach(self, parent):
37 ... self.item.x = None
38 ... def _pre_attach(self, parent):
39 ... self.item.x = self
40 >>> class NodeY(NodeMixin):
41 ... def __init__(self, item, parent=None):
42 ... self.item = item
43 ... self.parent = parent
44 ... def _pre_detach(self, parent):
45 ... self.item.y = None
46 ... def _pre_attach(self, parent):
47 ... self.item.y = self
48
49 Tree generation is simple:
50
51 >>> # X
52 >>> xa = NodeX(a)
53 >>> xb = NodeX(b, parent=xa)
54 >>> xc = NodeX(c, parent=xa)
55 >>> xd = NodeX(d, parent=xc)
56 >>> # Y
57 >>> yd = NodeY(d)
58 >>> yc = NodeY(c, parent=yd)
59 >>> yb = NodeY(b, parent=yd)
60 >>> ya = NodeY(a, parent=yb)
61
62 All tree functions as rendering and exporting can be used as usual:
63
64 >>> for row in RenderTree(xa):
65 ... print("%s%s" % (row.pre, row.node.item))
66 Item('A')
67 ├── Item('B')
68 └── Item('C')
69 └── Item('D')
70
71 >>> for row in RenderTree(yd):
72 ... print("%s%s" % (row.pre, row.node.item))
73 Item('D')
74 ├── Item('C')
75 └── Item('B')
76 └── Item('A')