补丁函数在运行时,简单的方法。
monki的Python项目详细描述
蒙基
补丁函数在运行时,简单的方法。
安装
pip install monki
基本用法
我们要修补以下功能:
def func():
print('First') # line 0
print('Second') # line 1
print('Third') # line 2
不同的修补方法:
import monki
# Add code at beginning or end
monki.patch(func, start="print('Starting')", end="print('Ending')")
func()
>>> 'Starting'
>>> 'First'
>>> 'Second'
>>> 'Third'
>>> 'Ending'
# Insert lines at any offset
monki.patch(func, insert_lines={1: "print('Injected line')", 2: "print('Another injection')"})
func()
>>> 'First'
>>> 'Injected line'
>>> 'Second'
>>> 'Another injection'
>>> 'Third'
# Let's patch a loop inside the function!
# To do so we need to insert the loop and indent a line to go inside it.
monki.patch(func, insert_lines={1: "for i in range(3):"}, indent_lines=[1])
func()
>>> 'First'
>>> 'Second'
>>> 'Second'
>>> 'Second'
>>> 'Third'
限制
- 目前,您无法对同一功能进行两次修补
- 有些边案例不能与闭包函数一起使用
- 可能只适用于cpython 3+。目前仅在CPython 3.7上测试