1

so I am using a third party python module I installed.

I initiate it like so:

from module import SomeClass

sc = SomeClass()
sc.process(text);

process() is using another method from another class in the same module called get_Text()

I want to modify the get_Text() method to return a modified string.

so sc.process(text) would return a different result than what it used to.

Do I use monkey patching? how would it work here? Do I copy paste the get_text() method and modify it and patch it at run time?

javastudent
  • 359
  • 1
  • 4
  • 12

2 Answers2

2

Explicit is better than implicit. Where possible, just use inheritance to alter the result of get_text

class SomeOtherClass(SomeClass):
    def get_text(self):
        return someClass.get_text(self) + ' bar'
Andrew Walker
  • 40,984
  • 8
  • 62
  • 84
  • 3
    I agree in principle, but it sounds like `get_text()` is being called in from another class -- in that case it might be expedient or even necessary to override `process()` itself. – Andrew Gorcester Dec 28 '13 at 09:25
  • @AndrewGorcester is correct. `get_text()` is in `AnotherClass`. `AnotherClass` is loaded by `SomeClass` in it's initialization. Would I need to import the `AnotherClass` and then override `get_text`? Reason I want to avoid overriding the whole `process()` is because it's quite lengthy and uses several other modules and packages and I don't want to copy paste that entire thing just to change a few things. – javastudent Dec 28 '13 at 21:48
  • @javastudent process() is instantiating AnotherClass. Unless you change process() or monkey-patch the module, process() will always instantiate the AnotherClass that you don't want, instead of some new variant that you create. I agree that overriding process() if that would involve a lot of copy-pasting is an ugly option, although that makes it sound like this module you're importing may not be terribly well architected (hard to tell for sure with so little context). But in that case, you're stuck with monkey-patching or finding another solution altogether. – Andrew Gorcester Dec 29 '13 at 00:46
1

Why Don't you give a try like this,

>>> import os
>>> os.getcwd()
'/home/sivacn'
>>> 
>>> def getcwd():
...     return 'Patched'
... 
>>> os.getcwd = getcwd
>>> 
>>> os.getcwd()
'Patched'
>>> 
Siva Cn
  • 929
  • 4
  • 10