Python Monkey Business
python-monkey-business is a Python package offering utility functions for monkey-patching code at runtime. It primarily provides a decorator to replace functions within classes or modules. The current version is 1.1.0, with the latest package upload on PyPI on July 11, 2024, though the project appears to have a very infrequent release cadence.
Warnings
- gotcha Monkey patching should be used with caution as it can lead to hard-to-debug issues and tightly couple your code to internal implementations of third-party libraries.
- gotcha By default, `avoid_doublewrap=True`, meaning functions and methods can only be patched once using `monkeybiz.patch`. Subsequent attempts to patch the same target will not take effect unless `avoid_doublewrap` is explicitly set to `False`.
- gotcha The `monkeybiz.patch` decorator expects the function being decorated to accept `original_fn` as its first argument, followed by `*args` and `**kwargs`, to allow calling the original implementation. Failing to include `original_fn` will prevent access to the unpatched function.
- gotcha The project's latest version (1.1.0) was uploaded to PyPI on July 11, 2024, but the initial release appears to be from March 2016. This suggests the library may not be under active development, and issues or new feature requests might not be addressed promptly.
Install
-
pip install python-monkey-business
Imports
- monkeybiz
import monkeybiz
- patch
from monkeybiz import patch
- unpatch
from monkeybiz import unpatch
Quickstart
import monkeybiz
# Assume 'foomodule' and 'FooClass' exist for demonstration
class FooClass:
def bar(self):
return "original"
# Patch a method in a class
@monkeybiz.patch(FooClass)
def bar(original_fn, *args, **kwargs):
print("Patched!")
return "patched_" + original_fn(*args, **kwargs)
instance = FooClass()
print(instance.bar()) # Should print 'Patched!' and 'patched_original'
monkeybiz.unpatch(FooClass, 'bar')
print(instance.bar()) # Should print 'original' again
# Example of patching a module-level function (requires a dummy module)
# import sys
# class DummyModule:
# def baz(): return 'original_module_baz'
# sys.modules['barmodule'] = DummyModule()
# import barmodule
#
# @monkeybiz.patch(barmodule)
# def baz(original_fn, *args, **kwargs):
# return 'patched_' + original_fn(*args, **kwargs)
#
# print(barmodule.baz()) # Should print 'patched_original_module_baz'
# monkeybiz.unpatch(barmodule, 'baz')