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

标签 python function serialization equality

我从这篇文章中找到了一个相当重要的答案: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/

相关文章:

python - 导入错误 : cannot import name HTTPSHandler using Brew

javascript - 检查一个数组是否是另一个数组的子集(但要检查一个属性)

java - Spring JSON序列化、Gson反序列化

c++ - 序列化原始 boost::variant 是否安全?

Python:如何在 POST 请求中发送 html 代码

python - 掩码二维数组保持形状

python - python strptime的自定义格式指令

perl - 如何将哈希传递给 Perl 中的函数?

c - C语言结构化数据的两个编程问题

Java : Serializable not working to save Object's states