Simon Willison’s Weblog

Subscribe
Atom feed for monkey-patching Random

9 posts tagged “monkey-patching”

2026

Introducing wrapture. New from Graham Dumpleton (of wrapt, mod_wsgi, and New Relic's Python agent fame), who describes Wrapture as taking the monkeypatching ideas from wrapt and extending them to apply to testing and tracing at the same time.

Wrapture (full documentation here) makes it easy to wrap any function or method such that all access can be traced, or can be overridden to return a different value.

It acts as both an alternative to unittest.mock and a way to implement tracing against an existing project:

Attaching observation to code you do not control, recording what flows through it, and doing so without disturbing the program being watched, is a problem I have never really stopped thinking about.

Wrapture includes OpenTelemetry support and even has an entirely configuration-based mechanism for adding tracing to an existing Python project, which looks like this:

capture = "summary"

[[observe]]
target = "domain:Calculator"
name = ["outer", "inner"]

[[sink]]
type = "jsonlines"
path = "trace.jsonl"

This is still a very young project - just a few weeks old - but it's off to a very promising start.

Interestingly, this is also Graham's first attempt at large entirely agent-driven project:

Every line of code and documentation in wrapture was written by an AI assistant working under my direction. I want to be upfront about that, and equally upfront about what it was not. This was not vibe coding, where a one-shot prompt produces a pile of generated code and the person driving hopes for the best because they lack the knowledge to judge what came back. Vibe coding has earned its bad reputation. I engineered wrapture carefully from the start. I have spent a long time in this particular corner of Python and knew exactly what the result needed to be, and the AI was the means of producing it rather than the source of the design.

In a follow-up post, Unit testing with wrapture, Graham shows the testing patterns supported by the new library:

def test_stub_with_wrapture():
    with wrapture.binding(
        Gateway, "charge"
    ).on_call.returns({
        "id": "stub", "amount": 0}
    ):
        assert OrderService().place(
            500
        )["id"] == "stub"

And this neat example of a test that calls and then modifies the return value from the original method:

def test_pinned_result_with_wrapture():
    charge = wrapture.binding(
        Gateway, "charge"
    )
    charge.on_call.transforms_result(
        lambda r: {**r, "id": "ch_TEST"}
    )
    with charge:
        assert OrderService().place(
           500
        ) == {
            "id": "ch_TEST", "amount": 500
        }

(In both of these examples the OrderService().place(...) method calls Gateway().charge(...).)

# 31st August 2026, 11:59 pm / graham-dumpleton, monkey-patching, python, testing, pytest, observability, ai-assisted-programming, agentic-engineering, opentelemetry

2018

s3monkey: A Python library that allows you to interact with Amazon S3 Buckets as if they are your local filesystem. (via) A particularly devious hack by Kenneth Reitz—provides a context manager within which various Python filesystem APIs such as open() and os.listdir() are monkeypatched to operate against an S3 bucket instead. Kenneth built it to make it easier to work with files from apps running on Heroku. Under the hood it uses pyfakefs, a filesystem mocking library originally released by Google.

# 21st February 2018, 5:54 pm / monkey-patching, python, s3, heroku

2010

Appending the request URL to SQL statements in Django. A clever frame-walking monkey-patch which pulls the most recent HttpRequest object out of the Python stack and adds the current request.path to each SQL query as an SQL comment, so you can see it in debugging tools such as slow query logs and the PostgreSQL “select * from pg_stat_activity” query.

# 2nd June 2010, 9:09 am / chris-lamb, debugging, django, monkey-patching, orm, postgresql, python, sql, recovered

What’s wrong with extending the DOM. Detailed explanation of the problems that crop up from extending built-in DOM objects using JavaScript, from Prototype developer kangax. Prototype 2.0 will be dropping this technique entirely—will MooTools follow suit?

# 11th April 2010, 10:03 pm / javascript, kangax, monkey-patching, mootools, prototype-js

2008

The Perl community has a long-standing love/hate-affair with making changes that impose "spooky action at a distance". They call it "black magic" and it is generally considered it a last resort. Black Magic that makes GLOBAL changes to things like inheritance is often characterised as being "Octarine" (see disk world novels), because it tends to work ok when there's only one person doing it, but start to mix a few together and KABOOM!

Adam Kennedy

# 22nd March 2008, 12:28 am / adam-kennedy, blackmagic, magic, monkey-patching, perl, ruby

Monkeypatching is Destroying Ruby (via) Deliberately provocative title, but makes a well considered case for restrained use of monkey patching in Ruby. Cultural norms around monkey patching seem to me to be one of the core differences between the Ruby and Python communities.

# 22nd March 2008, 12:27 am / ian-bicking, monkey-patching, python, ruby

Hacking Contributed Models. Neat Django trick using monkeypatching to make some minor tweaks to built-in contributed models such as auth or flatpages.

# 11th March 2008, 5:51 am / contrib, django, monkey-patching, python

Monkeypatching idioms—elegant or ugly? Guido offers a decorator and a metaclass as syntactic sugar for monkeypatching existing Python classes.

# 30th January 2008, 12:39 am / decorators, guido-van-rossum, idioms, metaclasses, monkey-patching, python

2007

Test stubbing httplib2. Nice demonstration of monkey-patching as part of unit testing in Python.

# 10th May 2007, 11:24 pm / httplib2, joe-gregorio, monkey-patching, python, testing