简体   繁体   中英

override (monkeypatch) a function in a 3rd party module used by other functions in that 3rd party module

I want to override a function internal to some 3rd party code. Here's an example of my intent.

(edit: I've corrected the spelling error below, and now this does work as intended)

#--- dog.py (3rd party code) ---
def _bark():
    print("WOOF!")

def make_it_bark():
    _bark()

#--- make_catlike.py (my code)---
import dog
dog._bark = lambda: print("MEOW") #<<-- 'bark' in original, so failed!!!!
dog.make_it_bark()
# edit: now prints out "MEOW" instead of "WOOF!" like I want

How do I get the 3rd party dog.py code to use my version of _bark?

[conclusion: This was only failing because of a spelling error . Thanks for the help!!]

You have a simple typo in make_catlike.py --- you're missing the leading underscore. The whole file should read:

#--- make_catlike.py (my code)---
import dog
dog._bark = lambda: print("MEOW")
#   ^-------- Underscore was missing.
dog.make_it_bark()  # Prints "MEOW".

Note that, in more complex cases, other kinds of things could go wrong...

For instance, if the behavior you want to change happens when the module is imported, altering that module's code after import dog returns won't help.

In code you provided make sure you have not forgotten underscore when redefining _bark function. If you want to change method of a class, a good idea would be to inherit that class and override method in your class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM