Search code examples
pythoncallbackmonkeypatching

Creating Python callback via monkey-patching


I'm creating an object that will represent some system info that can be changed outside of my program. Im thinking about allowing a callback function to be specified by the user of my code that will be called when a change is detected. This is what I have, which seems to work (the function doodie would be user supplied)

def doodie(cls):
    print cls.teststr

class Testarino(object):
    def __init__(self):
        self.teststr = 'Yay!'

    def callback(self):
        raise NotImplementedError

    def go(self):
         self.callback(self)

 tester = Testarino()
 tester.callback = doodie

 tester.go()

I thought about using a user supplied decorator, but I think that might be less intuitive for a user.

Is this the best way to do this? Is there a better way?


Solution

  • There is no need for monkey-patching here, it would be cleaner to add a set_callback() function to your Testarino class, like this:

    def doodie(cls):
        print cls.teststr
    
    class Testarino(object):
        def __init__(self):
            self.teststr = 'Yay!'
            self.callback = None
    
        def set_callback(self, callback):
            self.callback = callback
    
        def go(self):
             if self.callback is None:
                 raise NotImplementedError
             self.callback(self)
    
    tester = Testarino()
    tester.set_callback(doodie)
    
    tester.go()