gpt4 book ai didi

python - 在 JSON 中存储 Python 函数

转载 作者:太空宇宙 更新时间:2023-11-04 06:58:54 25 4
gpt4 key购买 nike

假设我有一个这样的 JSON 文件:

{
"x":5,
"y":4,
"func" : def multiplier(a,b):
return a*d
}

这过度简化了我想尝试和做的事情,但基本上我正在尝试
将 python UDF 故事化为 JSON 文件。有没有办法做到这一点,以便当我做:

with open('config.json') as f:
data = json.load(f)

我可以访问这些值并执行如下操作:

v1, v2 = data['x'], data['y']
mult = data['func']
print(mult(v1,v2))

要获得预期的输出:20

注意:据我了解,JSON 不存储函数,因此也许我可以将其存储为字符串,然后在我的 python 脚本中将字符串解析为函数?不太确定。

最佳答案

Python 有一个内置的模块名称 marshal 可以处理这个问题。

import marshal, ujson as json

def multiplier(a, b):
return a * b

x = {
"x":5,
"y":4,
"func" : marshal.dumps(multiplier.func_code)
}

x = json.dumps(x)
print(x)

为了取回它...

x = json.loads(x)
x = marshal.loads(x['func'])
# maybe save the function name in dict
func = types.FunctionType(x, globals(), "some_func_name")

print(func(2,4))

关于python - 在 JSON 中存储 Python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51936785/

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