Patchy

2.10.0 · active · verified Sun Apr 12

Patchy is a Python library that allows patching the inner source code of Python functions at runtime. Unlike traditional monkey patching, which replaces function objects, Patchy modifies the function's `__code__` attribute, ensuring that all references to the function (even those imported elsewhere) reflect the new behavior. It achieves this by using the standard `patch` command-line utility to apply diffs to the function's source code. The current version is 2.10.0, and it generally follows a release cadence tied to bug fixes and feature enhancements, compatible with Python 3.9 to 3.14.

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `patchy.patch()` to modify the runtime behavior of a Python function by applying a standard diff format string. The `patch` function takes the target function (or its dotted path as a string) and the patch text.

import patchy

def sample():
    return 1

print(f"Original output: {sample()}")

# Apply a patch to change the function's behavior
patchy.patch(
    sample,
    """\
def sample():
-    return 1
+    return 9001
""",
)

print(f"Patched output: {sample()}")

view raw JSON →