From 5d6036e75b8114cc5d422c3eb6775e56b0b25eaa Mon Sep 17 00:00:00 2001 From: Richard Hoekstra Date: Sat, 11 Apr 2020 13:22:24 -0700 Subject: [PATCH] - Added support for 'kwargs' in Tree.create_node. This is useful when you are subclassing treelib.Node extensively and do not want to make use of the 'data' property of treelib.Node. - Added a test case for the above mentioned 'kwargs'. --- tests/test_tree.py | 19 +++++++++++++++++++ treelib/tree.py | 4 ++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/tests/test_tree.py b/tests/test_tree.py index fcb67ce..eb7cfd3 100644 --- a/tests/test_tree.py +++ b/tests/test_tree.py @@ -617,6 +617,25 @@ class SubTree(Tree): node = tree.create_node() self.assertTrue(isinstance(node, SubNode)) + def test_subclassing_extra_kwargs(self): + class SubNode(Node): + def __init__(self, some_argument=None, **kwargs): + self.some_property = some_argument + super().__init__(**kwargs) + + class SubTree(Tree): + node_class = SubNode + + tree = SubTree() + node = tree.create_node(some_argument="some_value") + self.assertTrue(isinstance(node, SubNode)) + self.assertEqual(node.some_property, "some_value") + + tree = Tree(node_class=SubNode) + node = tree.create_node(some_argument="some_value") + self.assertTrue(isinstance(node, SubNode)) + self.assertEqual(node.some_property, "some_value") + def test_shallow_copy_hermetic_pointers(self): # tree 1 # Hárry diff --git a/treelib/tree.py b/treelib/tree.py index 6ee18c9..42535fc 100644 --- a/treelib/tree.py +++ b/treelib/tree.py @@ -336,12 +336,12 @@ def contains(self, nid): """Check if the tree contains node of given id""" return True if nid in self._nodes else False - def create_node(self, tag=None, identifier=None, parent=None, data=None): + def create_node(self, tag=None, identifier=None, parent=None, data=None, **kwargs): """ Create a child node for given @parent node. If ``identifier`` is absent, a UUID will be generated automatically. """ - node = self.node_class(tag=tag, identifier=identifier, data=data) + node = self.node_class(tag=tag, identifier=identifier, data=data, **kwargs) self.add_node(node, parent) return node