Bootstrap mechanism for monkey patches.
Maintained. Last release 2 months ago, commits in 1 of the last 26 weeks. Weaker on commit activity and contributor spread.
pip install autowraptautowrapt
Bootstrap mechanism for monkey patches.
autowrapt triggers the monkey patching of a Python application at interpreter startup, without the application itself being modified. It is a small companion to wrapt, whose post import hook mechanism does the actual work. You write the patches as post import hooks, expose them as entry points, and name the entry point group in an environment variable when running the application.
Installation
pip install autowrapt
autowrapt must be installed into the same Python installation or virtual
environment as the application it is to patch. Installing it puts two
startup files, autowrapt-init.start and autowrapt-init.pth, at the top
of site-packages, which is what triggers it at interpreter startup. Which
of them does the work depends on the Python version, as described below.
Usage
Write a post import hook for each module you want to patch. It is a function which takes the module as its only argument and is called immediately after the module is first imported.
# mycompany/patches.py
import wrapt
def patch_requests(module):
@wrapt.wrap_function_wrapper(module, "get")
def wrapper(wrapped, instance, args, kwargs):
print("GET", args[0] if args else kwargs.get("url"))
return wrapped(*args, **kwargs)
Register the hooks as entry points in the package which contains them. The entry point group name is yours to choose, and within it each entry point name is the module the hook is for.
# pyproject.toml
[project.entry-points."mycompany.patches"]
requests = "mycompany.patches:patch_requests"
Run the application with the AUTOWRAPT_BOOTSTRAP environment variable set
to the name of the entry point group.
AUTOWRAPT_BOOTSTRAP=mycompany.patches python app.py
More than one group can be named, separated by commas. Every entry point in
each group is registered as a post import hook, and each hook runs when, and
only when, its module is first imported. A module which is never imported
costs nothing. When the variable is not set, nothing is loaded beyond the
top level autowrapt package, which has no imports of its own.
Example
The package ships one example hook, registered under the
autowrapt.examples group against the module.