gpt4 book ai didi

Python:猴子修补函数的源代码

转载 作者:太空狗 更新时间:2023-10-30 00:04:37 25 4
gpt4 key购买 nike

函数源码可以加前缀和后缀吗?

我知道装饰器但不想使用它们(下面的最小示例没有说明原因,但我有我的理由)。

def f():
print('world')
g = patched(f,prefix='print("Hello, ");',suffix='print("!");')
g() # Hello, world!

这是我目前所拥有的:

import inspect
import ast
import copy
def patched(f,prefix,suffix):
source = inspect.getsource(f)
tree = ast.parse(source)
new_body = [
ast.parse(prefix).body[0],
*tree.body[0].body,
ast.parse(suffix).body[0]
]
tree.body[0].body = new_body
g = copy.deepcopy(f)
g.__code__ = compile(tree,g.__code__.co_filename,'exec')
return g

不幸的是,如果我使用它然后像上面那样调用 g() 没有任何反应; worldHello, world! 都没有打印出来。

最佳答案

以下是可以完成的粗略版本:

import inspect
import ast
import copy
def patched(f,prefix,suffix):
source = inspect.getsource(f)
tree = ast.parse(source)
new_body = [
ast.parse(prefix).body[0],
*tree.body[0].body,
ast.parse(suffix).body[0]
]
tree.body[0].body = new_body
code = compile(tree,filename=f.__code__.co_filename,mode='exec')
namespace = {}
exec(code,namespace)
g = namespace[f.__name__]
return g

def temp():
pass
def f():
print('world',end='')
g = patched(f,prefix='print("Hello, ",end="")',suffix='print("!",end="")')
g() # Hello, world!

调用compile 编译整个模块(用 表示)。然后这个模块在一个空的命名空间中执行,最终从中提取所需的功能。 (警告:如果 f 使用它们,命名空间将需要填充一些来自 f 的全局变量。)


经过一些更多的工作,这里是一个真实的例子,说明可以用它来做什么。它使用了上述原理的一些扩展版本:

import numpy as np
from playground import graphexecute
@graphexecute(verbose=True)
def my_algorithm(x,y,z):
def SumFirstArguments(x,y)->sumxy:
sumxy = x+y
def SinOfThird(z)->sinz:
sinz = np.sin(z)
def FinalProduct(sumxy,sinz)->prod:
prod = sumxy*sinz
def Return(prod):
return prod
print(my_algorithm(x=1,y=2,z=3))
#OUTPUT:
#>>Executing part SumFirstArguments
#>>Executing part SinOfThird
#>>Executing part FinalProduct
#>>Executing part Return
#>>0.4233600241796016

关键是,如果我重新调整 my_algorithm 的部分,我会得到完全相同的输出,例如:

@graphexecute(verbose=True)
def my_algorithm2(x,y,z):
def FinalProduct(sumxy,sinz)->prod:
prod = sumxy*sinz
def SumFirstArguments(x,y)->sumxy:
sumxy = x+y
def SinOfThird(z)->sinz:
sinz = np.sin(z)
def Return(prod):
return prod
print(my_algorithm2(x=1,y=2,z=3))
#OUTPUT:
#>>Executing part SumFirstArguments
#>>Executing part SinOfThird
#>>Executing part FinalProduct
#>>Executing part Return
#>>0.4233600241796016

这通过 (1) 获取 my_algorithm 的源并将其转换为 ast (2) 修补 my_algorithm 中定义的每个函数(例如 SumFirstArguments)以返回局部变量来实现(3) 根据输入和输出(由类型提示定义)决定 my_algorithm 各部分的执行顺序。此外,我还没有实现的一种可能性是并行执行独立的部分(例如 SumFirstArgumentsSinOfThird)。如果你想要 graphexecute 的源代码,请告诉我,我没有把它包含在这里,因为它包含很多与这个问题无关的东西。

关于Python:猴子修补函数的源代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53802169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com