Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a function call in an existing method

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.

like image 858
Mike Avatar asked Jul 12 '16 18:07

Mike


2 Answers

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 
…
like image 114
Marcus Müller Avatar answered Sep 24 '22 20:09

Marcus Müller


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/

like image 43
oz123 Avatar answered Sep 24 '22 20:09

oz123