gpt4 book ai didi

python - 完美序列化Python中的函数

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:00 24 4
gpt4 key购买 nike

我从这篇文章中找到了一个相当重要的答案:Is there an easy way to pickle a python function (or otherwise serialize its code)?

但是恢复后的功能似乎与原来的略有不同,未能通过我的测试。

这是示例代码:

import marshal

# serialize
f1 = lambda x: x == 0
c1 = marshal.dumps(f1.func_code)

# deserialize
f2 = types.FunctionType(c1, globals())

# test
c1 = marshal.dumps(f1.func_code)
c2 = marshal.dumps(f2.func_code)
assert c1 == c2 # fails

您知道如何改进序列化/反序列化以消除这种失真吗?

或者对平等测试部分有什么建议吗?

PS:仅考虑简单的 lambda,而不考虑复杂的闭包或普通函数。

最佳答案

问题是你不能直接比较函数变量,除非它们都引用同一个对象。相反,您应该比较 code 对象。

import types

original = lambda x: x == 0
code = original.func_code
recovered = types.FunctionType(code, globals())

print(original == recovered)
print(original.func_code == recovered.func_code)

输出:

False
True

让我们澄清一些。

a = lamdba : 1
aa = a
b = lambda : 1
c = lambda : 2

print(a == b)
print(a == aa)
print(a.func_code == b.func_code)
print(a.func_code == c.func_code)

输出:

False
True
True
False

编辑。我已经使用您的函数和 marshal 序列化对此进行了测试。工作得很好。

import marshal
import types

f = lambda x: x == 0

with open("test", "rw") as temp:
marshal.dump(f.func_code, temp)
ff = types.FunctionType(marshal.loads(temp.read()), globals())

print(f.func_code == ff.func_code)

输出

True

关于python - 完美序列化Python中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29249347/

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