Monkey patching changes what an object, class, module, or name does while a Python program is running, without changing its original source definition. It is a broad technique—not a Python keyword or a single library—and its safest everyday use is a temporary, tightly scoped replacement in a test. The key is to patch the name the code actually looks up, then restore it as soon as the test no longer needs the change.
What is monkey patching in Python?
A monkey patch adds, replaces, or removes behavior at runtime. For example, code can assign a new function to a class attribute or replace a module-level name with a test double. The original source file remains unchanged, but code that uses the patched object may behave differently for as long as the replacement is in effect.
The term describes a technique, not one particular tool. Pytest’s monkeypatch fixture and the standard-library unittest.mock.patch utility can both make temporary changes for tests. Monkey patching can also refer more broadly to runtime changes outside tests; those changes may persist for the life of a process or application if nothing restores the original behavior.
When should you use monkey patching?
Use a temporary patch when a test needs to control a dependency or environment that would otherwise be unpredictable, slow, unavailable, or costly. For example, you can replace an API call so a unit test does not contact a real service, provide a known environment variable, change a mapping, or control the current working directory.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
A mock is especially useful when the test must also check how the code interacted with a replacement—for example, whether it was called with particular arguments. If you control the code, passing dependencies in explicitly is usually a clearer long-term design than relying on global patches.
Patch the name the code looks up
Python names are bindings: several names can refer to the same original object. If a module imports a function directly, its local name is separate from the function’s name in the original module. Replacing the original module attribute later may not change what the importing module calls. Patch the lookup site used by the code under test.
Example: patch a directly imported function
Suppose report.py contains from os import getcwd and later calls getcwd(). The code looks up report.getcwd, so patch that name—not os.getcwd.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
# report.py
from os import getcwd
def current_directory():
return getcwd()
# test_report.py
import report
def test_current_directory(monkeypatch):
monkeypatch.setattr(report, "getcwd", lambda: "/tmp/test")
assert report.current_directory() == "/tmp/test"
Pytest restores the attribute when the test finishes. This example assumes the test file can import report and that pytest is installed and configured for the project.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Example: control an environment variable
Use pytest’s fixture when the function reads the environment at call time. This example gives the test a known value and lets pytest restore the prior environment afterward.
# settings.py
import os
def api_host():
return os.environ.get("API_HOST", "https://api.example.test")
# test_settings.py
import settings
def test_api_host_from_environment(monkeypatch):
monkeypatch.setenv("API_HOST", "https://test.example.test")
assert settings.api_host() == "https://test.example.test"
Choose pytest monkeypatch or unittest.mock.patch
Both approaches can temporarily change what code sees and restore it after a bounded scope. Choose based on the operation and whether you need interaction assertions.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
| Need | Useful choice | Why |
|---|---|---|
| Change an attribute, mapping, environment variable, import path, or current directory in a pytest test | monkeypatch fixture |
Provides methods for common changes and undoes them at test teardown. |
| Replace a target with a mock and assert calls or arguments | unittest.mock.patch |
It can create a mock replacement that records how it was used. |
| Contain an unusual or risky change in a small block | monkeypatch.context() or patch() as a context manager |
Both limit the change to a narrower scope and restore it when that scope ends. |
For example, a unittest.mock.patch context manager can replace the lookup site and let the test inspect the mock afterward:
from unittest.mock import patch
import report
def test_current_directory_with_mock():
with patch("report.getcwd", return_value="/tmp/test") as mock_getcwd:
assert report.current_directory() == "/tmp/test"
mock_getcwd.assert_called_once_with()
For either tool, patch where the system under test looks up the name. When a mock’s default flexibility could hide a changed interface, use spec or autospec where suitable, and keep integration tests for the connections between components.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsHow to keep patches safe
- Keep the scope small. Prefer a test fixture or context manager over a patch that remains active for an entire process. Pytest’s
monkeypatch.context()can further narrow a change within a test. - Let the tool clean up. Pytest undoes fixture changes at teardown;
unittest.mock.patchrestores the target when its decorator or context ends. Avoid manual restoration paths that can be skipped after an error. - Avoid broad patches to builtins. Replacing names such as
openorcompilecan interfere with pytest or libraries the test runner uses. If a patch is unavoidable, constrain it to the smallest block possible. - Prefer explicit dependencies in code you own. Passing a client, function, or other dependency into the code makes the dependency visible and easier to substitute deliberately.
- Do not mistake a passing unit test for compatibility. A permissive mock can continue to accept calls after the real interface changes. Use a suitable specification and integration coverage for the real boundary.
Common problems and fixes
The real function still runs
Cause: The patch changed a different name from the one the tested code uses, often because the code imported a function directly. Fix: Identify the module and attribute used at the call site, then patch that binding.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
A patch leaks into another test
Cause: A manual assignment or patch was not restored, or its scope is broader than intended. Fix: Use the pytest fixture, monkeypatch.context(), or a patch() context manager so cleanup happens at scope exit.
The test runner breaks after replacing a builtin
Cause: Pytest or a dependency uses the same builtin. Fix: Avoid the builtin patch if possible; otherwise use a narrowly scoped context and restore it immediately.
The test passes despite an interface change
Cause: The replacement accepts calls the real dependency would reject. Fix: Use spec or autospec where appropriate, and test integration with the actual component separately.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteBest Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Or skip the browser setup
For a different task—capturing a rendered webpage—ScreenshotNeo provides a screenshot API and MCP server. A single GET request can return an image or PDF. This does not replace Python monkeypatching; it is an option when the job is to capture a page rather than control a dependency in a test. See the ScreenshotNeo documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Before capture, it accepts cookie or consent banners and removes 60+ known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, with response headers indicating the page verdict and billing. Its MCP server offers screenshot and PDF tools to AI agents. The free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots.
Sign up for ScreenshotNeo’s free plan.
Frequently Asked Questions
Is monkey patching a Python keyword?
No. It is a general term for changing behavior at runtime, not a Python keyword.
Can monkey patching be used outside tests?
Yes. The term also covers runtime changes in application code, though persistent patches can make behavior harder to trace and maintain.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Does monkeypatching always mean using pytest?
No. Pytest’s fixture is one tool for temporary changes; monkey patching is the broader technique.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

