Networkx node deletion / removal callback
Question: 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](http://stackoverflow.com/questions/865115/how-do-i-correctly-clean-up-a-python-object)) 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?


Answer: 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.

