Question presented to candidate: "What is monkey patching? Show me how you would do it, tell me where it is genuinely useful, and why many teams treat it as a code smell outside of tests."
What a strong answer should cover:
- Monkey patching is replacing or adding an attribute (a method, function or value) on a class, instance or module at run time, without editing its source; it works because classes and modules are mutable objects whose attributes are looked up when used.
- Scope: patching a class affects every instance, old and new; patching an instance needs
types.MethodTypeto bindself; patching a module affects only code that looks the name up through the module. - The from-import trap:
from clock import nowcopies a reference, so patchingclock.nowdoes not affect it; withunittest.mock.patchyou patch where the name is looked up. - Main legitimate use is testing:
unittest.mock.patch/patch.object(stdlib since 3.3) or pytestmonkeypatch, which restore the original automatically; others are hotfixing a third-party bug and libraries like gevent that patch the stdlib. - Risks: global, invisible side effects, order-dependent behaviour, breakage on library upgrades, and built-in types such as
strcannot be patched at all.
Clarifying questions expected:
- Is this for tests or for production code? The acceptable answer differs.
Code / implementation expected: Yes β patch a class method and a module function, show the from-import trap, and the same done safely with unittest.mock.patch.