Monkey patching a class in another module in Python

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

    One another possible approach, very similar to Andrew Clark's one, is to use wrapt library. Among other useful things, this library provides wrap_function_wrapper and patch_function_wrapper helpers. They can be used like this:

    import wrapt
    import thirdpartymodule_a
    import thirdpartymodule_b
    
    @wrapt.patch_function_wrapper(thirdpartymodule_a.SomeClass, '__init__')
    def new_init(wrapped, instance, args, kwargs):
        # here, wrapped is the original __init__,
        # instance is `self` instance (it is not true for classmethods though),
        # args and kwargs are tuple and dict respectively.
    
        # first call original init
        wrapped(*args, **kwargs)  # note it is already bound to the instance
        # and now do our changes
        instance.a = 43
    
    thirdpartymodule_b.do_something()
    

    Or sometimes you may want to use wrap_function_wrapper which is not a decorator but othrewise works the same way:

    def new_init(wrapped, instance, args, kwargs):
        pass  # ...
    
    wrapt.wrap_function_wrapper(thirdpartymodule_a.SomeClass, '__init__', new_init)
    

提交回复
热议问题