WestHealth / pyvis

Python package for creating and visualizing interactive network graphs.
http://pyvis.readthedocs.io/en/latest/
BSD 3-Clause "New" or "Revised" License
940 stars 162 forks source link

Network not handling objects: assert isinstance(n_id, str) or isinstance(n_id, int) #282

Open matriculus opened 2 months ago

matriculus commented 2 months ago

I am building a networkx graph with objects based on custom class. The objects __str__ and __repr__ functions output only unique strings. The error arises when I migrate networkx graph to pyvis.

import networkx as nx
from pyvis.network import Network

class Account:
      def __init__(self, id):
            self.id =id

      def __str__(self) -> str:
            return f"Account: {id}"

      def __repr__(self) -> str:
            return self.__str__()

g = nx.Graph()
g.add_node(Account(1))
g.add_node(Account(2))
g.add_node(Account(3))
g.add_node(Account(4))
net = Network(
      directed=True,
      select_menu=True,
      filter_menu=True,
)
net.show_buttons()
net.from_nx(g)
net.toggle_physics(True)
net.show("test.html")

this gives an error

********************************
    assert isinstance(n_id, str) or isinstance(n_id, int)
AssertionError

It feels like Network is artificially forced to take in only str or int as nodes while networkx can take objects.

matriculus commented 2 months ago

add_node method could take the object and use the object's __str__ method to call and get id.