Python Monkey Business

1.1.0 · maintenance · verified Sun Apr 12

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

Install

Imports

Quickstart

Demonstrates how to use the `monkeybiz.patch` decorator to replace a method within a class and how to revert the patch using `monkeybiz.unpatch`.

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')

view raw JSON →