Fundamentals 4 min read

Understanding Monkey Patching in Python: Replacing json with ujson for Faster Serialization

This article explains the concept of monkey patching in Python, demonstrates how to replace the built‑in json module with the faster ujson library using a simple runtime patch, and shows performance improvements through code examples and timing tests.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Understanding Monkey Patching in Python: Replacing json with ujson for Faster Serialization

What is a monkey patch? Monkey patch (Monkey Patch) is a technique that dynamically replaces attributes or modules at runtime, effectively adding or changing program functionality.

Monkey Patch functionality overview allows modifying a class or module while the program is running.

Example shows replacing the standard json module with ujson using a simple monkey patch.

<code>"""
file:json_serialize.py
"""
import time
import json

# 时间测试装饰器
def run_time(func):
    def inner(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f'程序用时:{end_time - start_time}')
        return result
    return inner

@run_time
def json_dumps(obj):
    return json.dumps(obj)

# 生成测试字典
test_dict = {i: 1 for i in range(1, 10000001)}
</code>

Running the original program with json.dumps is relatively slow. The following script measures the time taken to serialize a large dictionary using the standard json module.

<code>"""
file:run.py
"""
from json_serialize import json_dumps, test_dict

print(f'json.dumps编码用时:', end='')
r1 = json_dumps(test_dict)
</code>

By applying a monkey patch, json.dumps is replaced with ujson.dumps , which significantly speeds up serialization.

<code>"""
file:run.py
"""
import json
import ujson
from json_serialize import json_dumps, test_dict

def monkey_patch_json():
    json.dumps = ujson.dumps

monkey_patch_json()
print(f'使用猴子补丁之后json.dumps编码用时:', end='')
json_dumps(test_dict)
</code>

After the patch, the json module in the project is effectively swapped for ujson, demonstrating how a monkey patch can globally affect a process and improve performance.

performancePythonJSONCodeExampleujsonMonkeyPatch
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.