I have an "image" class which exposes a method named ".extent()" and this class is a subclass of numpy.ndarray.
So, I can call
im = image( ( 256, 256 ), extent = ( 0.0, 3.14, -1.0, 1.0 ) )
matplotlib.pyplot.imshow( im, extent = im.extent() )
What I really would like to do is to inject code so that ".imshow()" in order to be able to call simply
matplotlib.pyplot.imshow( im )
and to have ".imshow()" to set the extent automatically.
Writing another function to do so is trivial, but I want to have "matplotlib.pyplot.imshow()" to do it.
So, my question is:
Is it possible to a model, written by me, to inject code inside a function from other module?
If so, how?
imshowis not defined as a protocol (such as theiteratorprotocol which works by thenextfunction or the descriptor protocol which works throughproperty) then you cannot expectimshowto disassemble objects that are passed to it and to behave different for different types of objects, beyond whatever extent this happens already in the source code ofimshow. If "showing" was implemented as an interface, as in say Haskell, then you could just ensure your class implements the interface. But this is not howmatplotlibhas chosen to work.imshow(as in Joran Beasley's answer) this usually causes more harm than good, especially for people picking up your code and expecting amatplotlibstandard function likeimshowto work with a certain calling signature and finding that instead it's been monkeypatched with your custom function. In most cases, it's better to just write a new function or have a class method that handles inducing the correctimshowcall.imshow. It was not implemented that way. It has no hooks for any code injection to make it behave differently (which is what it would have if it was an interface). Of course you can make a new function that first checks whether the argument is of your type, dispatches the right call, or else just callsimshowthe regular way. --- making a new function --- Which is something you said you did not want.