Change reference to function in run-time in Python
I need to change a call to a function inside another function during run-time. Consider the following code: def now(): print "Hello World!" class Sim: def __init__(self, arg, msg): self.msg = msg self.func = arg self.patch(self.func) def now(self): print self.msg def run(self): self.func() def patch(self, func): # Any references to the global now() in func # are replaced with the self.now() method. def myfunc(): now() Then ... >>> a = Sim(myfunc, "Hello Locals #1") >>> b = Sim(myfunc, "Hello Locals #2") >>> b.run() Hello Locals #2 >>> a.run() Hello Locals #1 One user has written code, myfunc()