92

我正在使用其他人编写的模块。我想修补__init__模块中定义的类的方法。我发现的展示如何做到这一点的例子都假设我自己会调用这个类(例如Monkey-patch Python class)。然而,这种情况并非如此。在我的情况下,该类是在另一个模块的函数中初始化的。请参阅下面的(非常简化的)示例:

第三方模块_a.py

class SomeClass(object):
    def __init__(self):
        self.a = 42
    def show(self):
        print self.a

第三方模块_b.py

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

我的模块.py

import thirdpartymodule_b
thirdpartymodule_b.dosomething()

有没有办法修改__init__方法,SomeClass以便dosomething从 mymodule.py 调用它时,例如打印 43 而不是 42?理想情况下,我能够包装现有的方法。

我无法更改thirdpartymodule*.py 文件,因为其他脚本依赖于现有功能。我宁愿不必创建自己的模块副本,因为我需要进行的更改非常简单。

编辑 2013-10-24

在上面的示例中,我忽略了一个小而重要的细节。SomeClassthirdpartymodule_b这样导入的:from thirdpartymodule_a import SomeClass.

要执行 FJ 建议的补丁,我需要替换副本thirdpartymodule_b,而不是thirdpartymodule_a. 例如thirdpartymodule_b.SomeClass.__init__ = new_init

4

6 回答 6

98

以下应该有效:

import thirdpartymodule_a
import thirdpartymodule_b

def new_init(self):
    self.a = 43

thirdpartymodule_a.SomeClass.__init__ = new_init

thirdpartymodule_b.dosomething()

如果您希望新的 init 调用旧的 init,请将new_init()定义替换为以下内容:

old_init = thirdpartymodule_a.SomeClass.__init__
def new_init(self, *k, **kw):
    old_init(self, *k, **kw)
    self.a = 43
于 2013-10-23T15:37:42.410 回答
52

使用mock图书馆。

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

或者

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()
于 2013-10-23T15:34:45.223 回答
6

另一种可能的方法,与Andrew Clark 的方法非常相似,是使用wrapt库。除了其他有用的东西,这个库还提供了wrap_function_wrapper帮助patch_function_wrapper程序。它们可以这样使用:

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()

或者有时您可能想要使用wrap_function_wrapper不是装饰器但以相同方式工作的东西:

def new_init(wrapped, instance, args, kwargs):
    pass  # ...

wrapt.wrap_function_wrapper(thirdpartymodule_a.SomeClass, '__init__', new_init)
于 2018-03-16T17:30:23.293 回答
3

很脏,但它有效:

class SomeClass2(object):
    def __init__(self):
        self.a = 43
    def show(self):
        print self.a

import thirdpartymodule_b

# Monkey patch the class
thirdpartymodule_b.thirdpartymodule_a.SomeClass = SomeClass2

thirdpartymodule_b.dosomething()
# output 43
于 2013-10-23T15:40:13.527 回答
1

一个稍微不那么hacky的版本使用全局变量作为参数:

sentinel = False

class SomeClass(object):
    def __init__(self):
        global sentinel
        if sentinel:
            <do my custom code>
        else:
            # Original code
            self.a = 42
    def show(self):
        print self.a

当哨兵为假时,它的行为与以前完全相同。如果它是真的,那么你就会得到你的新行为。在您的代码中,您将执行以下操作:

import thirdpartymodule_b

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

当然,在不影响现有代码的情况下进行适当的修复是相当微不足道的。但是您必须稍微更改其他模块:

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

并传递给init:

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

现有代码将继续工作 - 他们将不带参数调用它,这将保留默认的 false 值,这将保留旧的行为。但是您的代码现在有一种方法可以告诉整个堆栈,新行为是可用的。

于 2013-10-23T18:26:12.637 回答
1

这是我想出的一个使用 .monkeypatch 的Popen示例pytest

导入模块:

# must be at module level in order to affect the test function context
from some_module import helpers

一个MockBytes对象:

class MockBytes(object):

    all_read = []
    all_write = []
    all_close = []

    def read(self, *args, **kwargs):
        # print('read', args, kwargs, dir(self))
        self.all_read.append((self, args, kwargs))

    def write(self, *args, **kwargs):
        # print('wrote', args, kwargs)
        self.all_write.append((self, args, kwargs))

    def close(self, *args, **kwargs):
        # print('closed', self, args, kwargs)
        self.all_close.append((self, args, kwargs))

    def get_all_mock_bytes(self):
        return self.all_read, self.all_write, self.all_close

一家MockPopen收集假货的工厂:

def mock_popen_factory():
    all_popens = []

    class MockPopen(object):

        def __init__(self, args, stdout=None, stdin=None, stderr=None):
            all_popens.append(self)
            self.args = args
            self.byte_collection = MockBytes()
            self.stdin = self.byte_collection
            self.stdout = self.byte_collection
            self.stderr = self.byte_collection
            pass

    return MockPopen, all_popens

还有一个示例测试:

def test_copy_file_to_docker():
    MockPopen, all_opens = mock_popen_factory()
    helpers.Popen = MockPopen # replace builtin Popen with the MockPopen
    result = copy_file_to_docker('asdf', 'asdf')
    collected_popen = all_popens.pop()
    mock_read, mock_write, mock_close = collected_popen.byte_collection.get_all_mock_bytes()
    assert mock_read
    assert result.args == ['docker', 'cp', 'asdf', 'some_container:asdf']

这是相同的示例,但使用pytest.fixture它会覆盖内建Popen类导入helpers

@pytest.fixture
def all_popens(monkeypatch): # monkeypatch is magically injected

    all_popens = []

    class MockPopen(object):
        def __init__(self, args, stdout=None, stdin=None, stderr=None):
            all_popens.append(self)
            self.args = args
            self.byte_collection = MockBytes()
            self.stdin = self.byte_collection
            self.stdout = self.byte_collection
            self.stderr = self.byte_collection
            pass
    monkeypatch.setattr(helpers, 'Popen', MockPopen)

    return all_popens


def test_copy_file_to_docker(all_popens):    
    result = copy_file_to_docker('asdf', 'asdf')
    collected_popen = all_popens.pop()
    mock_read, mock_write, mock_close = collected_popen.byte_collection.get_all_mock_bytes()
    assert mock_read
    assert result.args == ['docker', 'cp', 'asdf', 'fastload_cont:asdf']
于 2017-01-12T20:47:20.300 回答