[Tutor] Best solution to modifying code within a distributed library

Steven D'Aprano steve at pearwood.info
Sat Sep 29 11:58:47 EDT 2018


On Wed, Sep 19, 2018 at 05:47:07PM -0400, Chip Wachob wrote:

[...]
> I've looked through the code in the FT232H.py file and found what I
> believe to be the culprit.
> 
> I would like to comment out line 340 (self.mpsse_write_gpio()) to
> prove that this is what is causing glitches that I do not want.

Since you don't have the source file, it might work to monkey patch the 
library. Beware: monkey patching is an advanced technique, hard to get 
right. But when it works, it can work very well.

https://en.wikipedia.org/wiki/Monkey_patch

Not to be confused with this:
https://en.wikipedia.org/wiki/Scratch_monkey


Let me assume that self.mpsse_write_gpio is *only* called from that one 
line 340, and nowhere else. If that's the case, you take your code which 
might look something like this:

import FT232H
obj = FT232H.SomeClass()  # initialise an instance
obj.run()

(let's say), and add a monkey patch that replaces the suspect 
mpsse_write_gpio method with a Do Nothing function:


import FT232H
obj = FT232H.SomeClass()  # initialise an instance
obj.mpsse_write_gpio = lambda self: None
obj.run()


The beauty of this is you don't need the source code! It all happens 
with the live code in the interpreter.

On the other hand, it might be that the suspect method is called from 
all over the place, and you only want to patch that *one* call on a 
single line. That's much harder and will require much ingenuity to 
solve. At that point, you might be better of just getting the source 
code and editing it.



-- 
Steve


More information about the Tutor mailing list