MyClass
is defined in module.py
. There is no way we can modify it. But we do know the Class definition looks like this:
class MyCla
This is an alternative to wim's answer that also involves monkey-patching. However, it does it through functionality provided by unittest.mock
. The advantage of this approach is that a context manager is used to automatically apply and remove the patch within a limited scope:
from unittest import mock
# This class would be defined in some third-party library
class MyClass:
def method(self, msg):
print('from method:', msg)
def function(msg):
print('from function:', msg)
old_method = MyClass.method
def new_method(self, msg):
old_method(self, msg)
function(msg)
# The patch is only applied within this scope
with mock.patch.object(MyClass, 'method', new_method):
foo = MyClass()
foo.method('message with patched')
# By this point MyClass is "back to normal"
print('---')
foo.method('message with original')
Output
from method: message with patched
from function: message with patched
---
from method: message with original