什么是monkey patch(猴子补丁)
monkey patch指的是在运行时动态替换,一般是替换(添加)类的方法、类或者模块都可以
首先使用系统模块的socket,打印socket.socket函数
然后在使用gevent模块的monkey.patch_socket()函数,打印socket.socket函数
socket.socket被动态替换成gevent的socket模块
演示代码如下
# -*- coding:utf8 -*- # /usr/bin/env python import socket print(socket.socket) print("after monkey patch") from gevent import monkey monkey.patch_socket() print(socket.socket) import select print(select.select) monkey.patch_select() print("after monkey patch") print(select.select)
<class 'socket.socket'>
after monkey patch
<class 'gevent._socket3.socket'>
<built-in function select>
after monkey patch
<function select at 0x108989510>
monkey patch使用自己代码实现
import time print(time.time()) def _time(): return 'abc' time.time = _time print(time.time())
运行时动态替换掉了对应函数