在python中完美序列化函数

在python中完美序列化函数,python,function,serialization,equality,Python,Function,Serialization,Equality,我从这篇文章中找到了一个相当不错的答案: 然而,恢复后的函数似乎与原来的函数略有不同,这使我的测试失败 以下是示例代码: 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 = marsha

我从这篇文章中找到了一个相当不错的答案:

然而,恢复后的函数似乎与原来的函数略有不同,这使我的测试失败

以下是示例代码:

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
False
True
True
False
让我们澄清一下

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
False
True
True
False
编辑。我已经用您的函数和
封送
序列化测试了这一点。很好用

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

好的,看来marshal做了一些奇怪的事情,因为marshal.dumps(original.func_代码)==marshal.dumps(recovered.func_代码)返回False更准确地说,marshal.loads(marshal.dumps(original.func_代码))==original.func_代码返回FalseFalse@Sam嗯,对我有用。我在答案中加了一个例子。