Implementation:AUTOMATIC1111 Stable diffusion webui Module Method Patcher
| Knowledge Sources | |
|---|---|
| Domains | Metaprogramming, Runtime_Modification |
| Last Updated | 2025-05-15 00:00 GMT |
Overview
Provides a key-based system for safely replacing and restoring functions on modules and classes at runtime, with tracking of original functions to prevent double-patching.
Description
The Monkey Patching module implements a controlled mechanism for runtime function replacement (monkey patching) with full undo capability. The patch function replaces a named attribute on an object (module or class) with a new function, stores the original in a global originals defaultdict keyed by a caller identifier and an (object, field) tuple, and returns the original function. It raises a RuntimeError if the same caller attempts to patch the same function twice without undoing it first. The undo function restores the original function and removes it from the tracking dictionary. The original function allows retrieval of the stored original without undoing the patch. This system is used throughout the WebUI for hijacking functions in external libraries (such as PyTorch and CLIP) to customize behavior.
Usage
Use this module when you need to temporarily replace a function in a third-party library or internal module and want a safe way to undo the change later. The key-based system prevents conflicts between different callers patching the same function.
Code Reference
Source Location
- Repository: AUTOMATIC1111_Stable_diffusion_webui
- File: modules/patches.py
- Lines: 1-64
Signature
def patch(key, obj, field: str, replacement) -> callable
def undo(key, obj, field: str) -> None
def original(key, obj, field: str) -> callable | None
Import
from modules.patches import patch, undo, original
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| key | any | Yes | Identifier for the caller performing the patch (typically __name__) |
| obj | module or class | Yes | The module or class containing the function to replace |
| field | str | Yes | Name of the attribute/function to replace |
| replacement | callable | Yes | The new function to substitute in (used by patch only) |
Outputs
| Name | Type | Description |
|---|---|---|
| original_func | callable | The original function that was replaced (returned by patch) |
| stored_original | callable or None | The stored original function (returned by original), or None if no patch exists |
Usage Examples
from modules.patches import patch, undo, original
import torch
# Patch a function
original_linear = patch(
__name__,
torch.nn.functional,
"linear",
my_custom_linear
)
# Retrieve the original without undoing
orig = original(__name__, torch.nn.functional, "linear")
# Undo the patch
undo(__name__, torch.nn.functional, "linear")