given a module with a class Foo with a method that calls a function bar defined in the module scope, is there a way to substitute bar for a different function without modification to the module?
class Foo(object):
def run(self):
bar()
def bar():
return True
I then have a an instance of Foo for which I would like to substitute a function baz() for bar() without having to modify the Foo class.
Let's assume your module is called deadbeef, and you're using it like this
import deadbeef
…
foo_instance = deadbeef.Foo()
Then you could do
import deadbeef
deadbeef.bar = baz
…
You can monkey patch Foo at run time, and override the method run.
For example if foo is instance of Foo you can do:
def run(obj):
baz()
foo.run = run
Next time you call foo.run it will invoke baz.
See more here http://blog.tryolabs.com/2013/07/05/run-time-method-patching-python/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With