[Interview Qn] What Is Monkey Patching?

Liu Zuo Lin
Level Up Coding
Published in
3 min read5 days ago

Monkey patching refers to a technique where we dynamically modify code behaviour at runtime.

We probably use this the most during testing rather than in the actual application code (doing monkey patching in app code is bad practice)

A simple dummy example

Let’s say we have some API endpoint that gives us some fruits eg. https://fruits.com/api/fruits which returns something like:

{
"fruits": ["apple", "orange", "pear"]
}

^ tho this fruits list might change once per few days

And we have a dummy function that uses this API.

import requests

def check_fruit(fruit: str):

URL = 'https://fruits.com/api/fruits'
fruits_data = requests.get(URL).json()['fruits']

return {
'valid': fruit in fruits_data,
'fruits': fruits_data
}

x = check_fruit('pineapple')
print(x)

# {'valid': False, 'fruits': ['apple', 'orange', 'pear']}

Next, we want to test the check_fruit() function

Let’s assume we use pytest for unit testing.

We could write some function like this:

from somewhere import check_fruit

def test_check_fruit():

res = check_fruit('apple')…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

My Substack Newsletter: https://zlliu.substack.com | 101 Things I Never Knew About Python: https://payhip.com/b/vywcf