javastudent
javastudent

Reputation: 369

Python: override a third party module method?

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?

Upvotes: 1

Views: 3171

Answers (2)

Siva Cn
Siva Cn

Reputation: 947

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'
>>> 

Upvotes: 1

Andrew Walker
Andrew Walker

Reputation: 42470

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'

Upvotes: 2

Related Questions