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.
pip install patchyVerified import paths — ran on the pinned version, not inferred.
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.
Ensure patches are as minimal as possible and carefully test against library updates. Consider using version control to manage patches and their corresponding library versions.
Always start your `patch_text` triple-quoted string with a backslash immediately after the opening quotes, followed by a newline, to ensure correct indentation handling.
Use Patchy for targeted, infrequent runtime modifications rather than highly performance-critical operations. Ensure the `patch` command-line utility is available in the execution environment.
Understand Patchy's specific use case (function source patching) and choose other tools for broader file or repository-level patching requirements.