langlauf.io
langlauf.io

Reputation: 3221

Networkx node deletion / removal callback

Given a directed networkx graph. I would like to have a function, say "abc()", called for every node that is deleted from the graph. I went through the networkx documentation but did not find any such callback feature.

What I considered:

  1. Adding a call to abc() to the __del__() (deconstructor) method of the object associated with a node. Yet, besides the pitfalls of using __del__() (see e.g. here) this does not work if any links to the node object exist somewhere in memory.
  2. Subclassing the networkx.DiGraph() class and overriding the remove_node() method. Drawback: This would require overriding all methods that remove a node, e.g. remove_nodes_from (are there any more?)
  3. As the networkx graph implementation is based on dictionaries, it could be a solution to somehow 'hook' the del function of this dictionary. Interfering this deep into networkx seems inappropriate though.

What is the easiest way to implement a callback function which is called everytime a networkx node is deleted?

Upvotes: 0

Views: 560

Answers (1)

Aric
Aric

Reputation: 25309

In this case you only need to subclass two methods. Here is an example from networkx import DiGraph

class RemoveNodeDiGraph(DiGraph):
    def remove_node(self, n):
        DiGraph.remove_node(self, n)
        print("Remove node: %s"%n)

    def remove_nodes_from(self, nodes):
        for n in nodes:
            self.remove_node(n)

if __name__=='__main__':
    G = RemoveNodeDiGraph()
    G.add_node('foo')
    G.add_nodes_from('bar',weight=8)
    G.remove_node('b')
    G.remove_nodes_from('ar')

This won't be quite as fast as the original methods in the DiGraph class (especially remove_nodes_from()) but unless you have very large graphs it won't likely be significant. If you need better performance you could copy the code directly from those methods instead of calling the superclass.

Upvotes: 1

Related Questions