Debian Codegraph @

docs/tricks/weightededges.rst

raw
1 Weighted Edges
2 ==============
3
4 **Application**: Add weight to edges and make use of them.
5
6 As every node has just one parent, the easiest way to handle edge weights is to
7 store them in the child node.
8 If a child node is detached from its parent, the weight attribute can be cleared
9 automatically by `Node._post_detach`.
10
11 >>> from anytree import NodeMixin, RenderTree
12 >>> class WNode(NodeMixin):
13 ...
14 ... def __init__(self, foo, parent=None, weight=None):
15 ... super(WNode, self).__init__()
16 ... self.foo = foo
17 ... self.parent = parent
18 ... self.weight = weight if parent is not None else None
19 ...
20 ... def _post_detach(self, parent):
21 ... self.weight = None
22
23 An example tree:
24
25 >>> a = WNode("a")
26 >>> a0 = WNode("a0", parent=a, weight=2)
27 >>> a1 = WNode("a1", parent=a, weight=3)
28 >>> a1a = WNode("a1a", parent=a1)
29 >>> a2 = WNode("a2", parent=a)
30 >>> for pre, _, node in RenderTree(a):
31 ... print("%s%s (%s)" % (pre, node.foo, node.weight or 0))
32 a (0)
33 ├── a0 (2)
34 ├── a1 (3)
35 │ └── a1a (0)
36 └── a2 (0)
37
38 >>> from anytree.exporter import DotExporter
39 >>> DotExporter(a,
40 ... nodenamefunc=lambda node: node.foo,
41 ... edgeattrfunc=lambda parent, child: "style=bold,label=%d" % (child.weight or 0)
42 ... ).to_picture("weight.png") # doctest: +SKIP
43
44 .. image:: ../static/weight.png