Reputation: 2564
If I import a package, let's say networkx.
How to override one method inside it so that it's the one called by every other function inside the package ?
Example :
import networkx as nx
def _draw_networkx_nodes(G, pos,
nodelist=None,
node_size=300,
node_color='r',
node_shape='o',
alpha=1.0,
cmap=None,
vmin=None,
vmax=None,
ax=None,
linewidths=None,
label=None,
**kwds):
print 'OK'
nx.draw_networkx_nodes = _draw_networkx_nodes
G = nx.Graph()
G.add_edge('A','B')
nx.draw(G)
I want the method draw to call other methods that will call my overriden function
Upvotes: 2
Views: 185
Reputation: 3428
This is a problem of how methods are called in python. You're patching the draw_networkx_nodes
in the networkx
top module, but it doesn't originate from that top-module: The networkx.draw
method is imported from networkx.drawing.nx_pylab
. This draw
method down there locally calls draw_networkx
which locally (still down in that file) calls draw_networkx_nodes
. This is why modifying the alias that was imported in networkx/__init__.py
doesn't work: it's never called internally.
So in other: If you want to patch a method of a library, see which sub-module it's originating from and patch it there.
So in this case:
In [6]: nx.drawing.nx_pylab.draw_networkx_nodes = _draw_networkx_nodes
In [7]: nx.draw(G)
OK
Upvotes: 1