How to replace a function call in an existing method

given a module with class Foo with a method that calls a function bardefined in the module area, is there a way to replace it barwith another function without changing the module?

class Foo(object):
    def run(self):
        bar()

def bar():
    return True

Then I have an instance Foofor which I would like to replace the function baz()with bar()without changing the class Foo.

+4
source share
3 answers

Suppose your module is called deadbeefand you use it that way

import deadbeef
foo_instance = deadbeef.Foo()

Then you could do

import deadbeef
deadbeef.bar = baz 
+9
source

You can execute the monkey patch Fooat run time and override the method run.

, Foo Foo, :

def run(obj): 
    baz()

foo.run = run

foo.run baz.

http://blog.tryolabs.com/2013/07/05/run-time-method-patching-python/

+4

I asked for something similar recently, and staticmethod was the answer (because your baz and bar don't seem to be methods). Basically, you want to do something like a strategy template and call another function from run ().

def bar():
    print "I am bar()"
    return True

def baz():
    print "I am baz()"
    return True

class Foo(object):

    # default to running bar.
    torun = staticmethod(bar)

    def run(self):
        self.torun()

foo = Foo()

foo.run()

foo2 = Foo()
foo2.torun = baz

foo2.run()

output:

I am bar()
I am baz()

You can assign almost anything you want to your foo instance, including functions defined in another module. And the launch may take * args and ** kwds for more flexibility.

0
source

All Articles