Monkey patching a class in another module in Python

前端 未结 6 1067
走了就别回头了
走了就别回头了 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:29

    Use mock library.

    import thirdpartymodule_a
    import thirdpartymodule_b
    import mock
    
    def new_init(self):
        self.a = 43
    
    with mock.patch.object(thirdpartymodule_a.SomeClass, '__init__', new_init):
        thirdpartymodule_b.dosomething() # -> print 43
    thirdpartymodule_b.dosomething() # -> print 42
    

    or

    import thirdpartymodule_b
    import mock
    
    def new_init(self):
        self.a = 43
    
    with mock.patch('thirdpartymodule_a.SomeClass.__init__', new_init):
        thirdpartymodule_b.dosomething()
    thirdpartymodule_b.dosomething()
    

提交回复
热议问题