SlideShare a Scribd company logo
monkey-patching:
amagictrickor
apowerfultool?
Elizaveta Shashkova

@lisa_shashkova
elizaveta.shashkova@jetbrains.com
bio
• Software Developer of PyCharm IDE at JetBrains
• Debugger used in PyDev & PyCharm
2
Monkey-patching is a dynamic modification of a class
or a module at runtime
def safe_sqrt(num):
# doesn’t throw exception if num < 0
if num < 0:
return math.nan
return math.original(num)
>>> import math
>>> math.original = math.sqrt
>>> math.sqrt = safe_sqrt
monkey-patching
monkey-patching
• Guerilla patch
• Does something secretly and incompatibly
with others
• Gorilla patch
• Monkey patch
otherlanguages
Ruby
class String
def upcase
self.reverse
end
end
> puts "hello".upcase

"olleh"
python
Explicit is better than implicit
whatcanwepatch?
Everything!
whatcanwepatch?
Almost
Everything!
We can’t patch built-ins defined in C
lightsideof
monkey-patching
9
darksideof
monkey-patching
•Workaround for bugs in third-party code
lightside
•Workaround for bugs in third-party code
• Don’t forget to fix and create a pull request!
lightside
•Workaround for bugs in third-party code
• Don’t forget to fix and create a pull request!
•Code instrumentation
lightside
•Workaround for bugs in third-party code
• Don’t forget to fix and create a pull request!
•Code instrumentation
•Testing
lightside
•Workaround for bugs in third-party code
• Don’t forget to fix and create a pull request!
•Code instrumentation
•Testing
•Changing of standard modules
lightside
examples
lightside:catchingnew
process
lightside:newprocess
class ProcessManager:
def __init__(self, system_fork):
self.system_fork = system_fork
def do_fork(self):
pid = self.system_fork()
if pid == 0:
# child process
start_tracing()
return pid
import os
manager = ProcessManager(os.fork)
os.fork = manager.do_fork



os.fork()
#tracing in a new process
lightside:newprocess
lightside:importhook
•How to patch a module as soon as possible?
•Patch it right after importing
lightside
lightside:importhook
class ImportHookManager:
def __init__(self, system_import):
self.system_import = system_import
def do_import(self, name):
module = self.system_import(name)
if name == "os":

orig_fork = module.fork

module.fork = ProcessManager(orig_fork).do_fork
return module
lightside:importhook
import builtins
manager = ImportHookManager(builtins.__import__)
builtins.__import__ = manager.do_import





import os

# module is patched as soon as it is imported
lightside:gevent
lightside:gevent
● gevent provides asynchronous I/O
● Blocking system calls in the standard library
import socket
● Replace with gevent modules
from gevent import socket
lightside:gevent
! The simplest way
from gevent import monkey

monkey.patch_socket()
•Workaround for bugs in third-party code
•Code instrumentation
•Testing
•Changing of standard modules
lightside
lightsideof
monkey-patching
27
darksideof
monkey-patching
darkside
Implicitness
darkside
• Implicit changes
darkside
• Implicit changes
• Undocumented changes
darkside
• Implicit changes
• Undocumented changes
• Unpredictable behaviour
darkside
• Implicit changes
• Undocumented changes
• Unpredictable behaviour
• Patching the same
examples
darkside:gevent
darkside:gevent
• Patches standard modules
socket, thread, time and others
• Should be done as soon as possible
runningcodeunderdebugger
• Event loop in debugger
Based on threads
• Event loop in user’s code
Based on gevent loop

They should be separated
theproblem
Save the original versions of modules and use them
with the patched versions
importinginpython
# very simple version

def import_module(name):
if name in sys.modules:
return sys.modules[name]
module = internal_import(name)
sys.modules[name] = module
return module
savemodules
saved_modules.py:



import socket
# save the module object
save = sys.modules.pop('socket', None)
# it's not in sys.modules, reimport
import socket as socket_saved
# put the module available for patching
sys.modules['socket'] = save
savemodules
from saved_modules import saved_socket

import socket



# it will patch socket in sys.path

gevent.patch_socket()



# the patched function

socket.create_connection()
# the original function

saved_socket.create_connection()
theproblem
Save the original versions of modules and use them
with the patched versions
Solved!
● Implicit changes
● Undocumented
changes
● Broken readability
● Incompatibility with
other patches
● Workaround for bugs in
third-party code
● Code instrumentation
● Testing
● Changing of standard
modules
lightsideof
monkey-patching
darksideof
monkey-patching
whenshouldiuseit?
If and only if there are no other solutions for
the problem
lightsideof
monkey-patching
44
darksideof
monkey-patching
lightsideof
monkey-patching
45
darksideof
monkey-patching
Elizaveta Shashkova
@lisa_shashkova

More Related Content

PPTX
Se eu me humilhar
PPTX
Liberta-me de Mim
PPTX
Me Da Poder de Filho - Marcelo Aguiar
PPTX
React Hooks
PPTX
React Hooks
PPT
Como é precioso
PDF
Asynchronous JavaScript Programming
PPTX
Soap, wsdl et uddi
Se eu me humilhar
Liberta-me de Mim
Me Da Poder de Filho - Marcelo Aguiar
React Hooks
React Hooks
Como é precioso
Asynchronous JavaScript Programming
Soap, wsdl et uddi

What's hot (14)

PDF
The Uniform Access Principle
PDF
Decoupling Drupal mit dem Lupus Nuxt.js Drupal Stack
PPT
Communiceren met kinderen met een ontwikkelingsachterstand
PPT
Eu nasci de novo
PDF
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
PPTX
Vai dar tudo certo waldecy aguiar
PPTX
O homem das mãos furada
PPTX
Você me leva ao deserto ministerio zoe
PDF
Kotlin and Domain-Driven Design: A perfect match - Kotlin Meetup Munich
PDF
Les quinze oraisons de Sainte Brigitte de Suède.
PPTX
Functions in PHP.pptx
PPT
Deus da minha vida
PDF
Lightweight Xtext Editors as SWT Widgets
PPTX
Não se Turbe Vosso Coração - Heloísa Rosa
The Uniform Access Principle
Decoupling Drupal mit dem Lupus Nuxt.js Drupal Stack
Communiceren met kinderen met een ontwikkelingsachterstand
Eu nasci de novo
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Vai dar tudo certo waldecy aguiar
O homem das mãos furada
Você me leva ao deserto ministerio zoe
Kotlin and Domain-Driven Design: A perfect match - Kotlin Meetup Munich
Les quinze oraisons de Sainte Brigitte de Suède.
Functions in PHP.pptx
Deus da minha vida
Lightweight Xtext Editors as SWT Widgets
Não se Turbe Vosso Coração - Heloísa Rosa
Ad

Similar to Monkey-patching in Python: a magic trick or a powerful tool? (20)

PDF
Demystifying Binary Reverse Engineering - Pixels Camp
PPTX
GCC Summit 2010
PDF
Effective code reviews
PDF
How to really obfuscate your pdf malware
PDF
How to really obfuscate your pdf malware
PDF
Rainbow Over the Windows: More Colors Than You Could Expect
PDF
Common technique in Bypassing Stuff in Python.
PPTX
Adventures in Asymmetric Warfare
PDF
Digging for Android Kernel Bugs
PDF
Instruction Combine in LLVM
PDF
Byteman and The Jokre, Sanne Grinovero (JBoss by RedHat)
PPTX
Scratch pcduino
PDF
Pharo Virtual Machine: News from the Front
PDF
Us 17-krug-hacking-severless-runtimes
PDF
OT Security - h-c0n 2020
PDF
Expert JavaScript Programming
PDF
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
PDF
Infecting the Embedded Supply Chain
PDF
Packaging perl (LPW2010)
PDF
Android antipatterns
Demystifying Binary Reverse Engineering - Pixels Camp
GCC Summit 2010
Effective code reviews
How to really obfuscate your pdf malware
How to really obfuscate your pdf malware
Rainbow Over the Windows: More Colors Than You Could Expect
Common technique in Bypassing Stuff in Python.
Adventures in Asymmetric Warfare
Digging for Android Kernel Bugs
Instruction Combine in LLVM
Byteman and The Jokre, Sanne Grinovero (JBoss by RedHat)
Scratch pcduino
Pharo Virtual Machine: News from the Front
Us 17-krug-hacking-severless-runtimes
OT Security - h-c0n 2020
Expert JavaScript Programming
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Infecting the Embedded Supply Chain
Packaging perl (LPW2010)
Android antipatterns
Ad

Recently uploaded (20)

PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
medical staffing services at VALiNTRY
PDF
System and Network Administraation Chapter 3
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Introduction to Artificial Intelligence
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
Essential Infomation Tech presentation.pptx
PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
history of c programming in notes for students .pptx
PDF
AI in Product Development-omnex systems
PDF
System and Network Administration Chapter 2
PDF
Digital Strategies for Manufacturing Companies
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
Upgrade and Innovation Strategies for SAP ERP Customers
medical staffing services at VALiNTRY
System and Network Administraation Chapter 3
How Creative Agencies Leverage Project Management Software.pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Introduction to Artificial Intelligence
CHAPTER 2 - PM Management and IT Context
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PTS Company Brochure 2025 (1).pdf.......
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Softaken Excel to vCard Converter Software.pdf
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Essential Infomation Tech presentation.pptx
Operating system designcfffgfgggggggvggggggggg
history of c programming in notes for students .pptx
AI in Product Development-omnex systems
System and Network Administration Chapter 2
Digital Strategies for Manufacturing Companies
VVF-Customer-Presentation2025-Ver1.9.pptx

Monkey-patching in Python: a magic trick or a powerful tool?