Skip to the solution
MediumDSA12 min read

What is monkey patching in Python?

179 views

The problem

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.MethodType to bind self; patching a module affects only code that looks the name up through the module.
  • The from-import trap: from clock import now copies a reference, so patching clock.now does not affect it; with unittest.mock.patch you patch where the name is looked up.
  • Main legitimate use is testing: unittest.mock.patch / patch.object (stdlib since 3.3) or pytest monkeypatch, 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 str cannot 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.

  • monkey-patching

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonPatching a class, an instance and a module, and the from-import trap
Pythonunittest.mock.patch: lookup site, restore on error, autospec

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 103 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What is a context manager?

Continue