Monkey patching a class in another module in Python

前端 未结 6 1065
走了就别回头了
走了就别回头了 2020-11-27 12:07

I\'m working with a module written by someone else. I\'d like to monkey patch the __init__ method of a class defined in the module. The examples I have found sh

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 12:38

    One only slightly-less-hacky version uses global variables as parameters:

    sentinel = False
    
    class SomeClass(object):
        def __init__(self):
            global sentinel
            if sentinel:
                
            else:
                # Original code
                self.a = 42
        def show(self):
            print self.a
    

    when sentinel is false, it acts exactly as before. When it's true, then you get your new behaviour. In your code, you would do:

    import thirdpartymodule_b
    
    thirdpartymodule_b.sentinel = True    
    thirdpartymodule.dosomething()
    thirdpartymodule_b.sentinel = False
    

    Of course, it is fairly trivial to make this a proper fix without impacting existing code. But you have to change the other module slightly:

    import thirdpartymodule_a
    def dosomething(sentinel = False):
        sc = thirdpartymodule_a.SomeClass(sentinel)
        sc.show()
    

    and pass to init:

    class SomeClass(object):
        def __init__(self, sentinel=False):
            if sentinel:
                
            else:
                # Original code
                self.a = 42
        def show(self):
            print self.a
    

    Existing code will continue to work - they will call it with no arguments, which will keep the default false value, which will keep the old behaviour. But your code now has a way to tell the whole stack on down that new behaviour is available.

提交回复
热议问题