From 39f8553cb4033244215a0afa1bf358fe87ca9b4a Mon Sep 17 00:00:00 2001 From: Brennen Raimer <5969754+norweeg@users.noreply.github.com> Date: Wed, 3 Apr 2024 10:27:39 -0400 Subject: [PATCH] fixes #276 * removes unnecessary and silent type conversion of numeric node IDs * add_edges using node IDs' original type no longer raises exception * refactored coincidental inappropriate usage of assert for type-checking/control logic in add_node and add_nodes to raise appropriate exceptions instead --- pyvis/network.py | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/pyvis/network.py b/pyvis/network.py index 8deb915..68a21d5 100644 --- a/pyvis/network.py +++ b/pyvis/network.py @@ -233,7 +233,8 @@ def add_node(self, n_id, label=None, shape="dot", color='#97c2fc', **options): :type x: num (optional) :type y: num (optional) """ - assert isinstance(n_id, str) or isinstance(n_id, int) + if not isinstance(n_id, (str, int)): + raise TypeError("Node IDs should be of type str or int") if label: node_label = label else: @@ -274,28 +275,23 @@ def add_nodes(self, nodes, **kwargs): valid_args = ["size", "value", "title", "x", "y", "label", "color", "shape"] for k in kwargs: - assert k in valid_args, "invalid arg '" + k + "'" + if not k in valid_args: + raise ValueError("invalid arg '" + k + "'") nd = defaultdict(dict) - for i in range(len(nodes)): + for i, node in enumerate(nodes): for k, v in kwargs.items(): - assert ( - len(v) == len(nodes) - ), "keyword arg %s [length %s] does not match" \ - "[length %s] of nodes" % \ - ( - k, len(v), len(nodes) - ) - nd[nodes[i]].update({k: v[i]}) + if not len(v) == len(nodes): + raise ValueError( + f"keyword arg {k} [length {len(v)}] does not match " + f"[length {len(nodes)}] of nodes" + ) + nd[node].update({k: v[i]}) for node in nodes: - # check if node is `number-like` - try: - node = int(node) - self.add_node(node, **nd[node]) - except: - # or node could be string - assert isinstance(node, str) + if not isinstance(node, (str, int)): + raise TypeError("Node IDs should be of type str or int") + else: self.add_node(node, **nd[node]) def num_nodes(self):