完美序列化python中的函数 [英] perfectly serialize a function in python

查看:218
本文介绍了完美序列化python中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这篇文章中找到了一个相当不错的答案:是否有一种简单的方法来腌制python函数(或以其他方式序列化其代码)?

I found a considerable answer from this post: Is there an easy way to pickle a python function (or otherwise serialize its code)?

但是,恢复的功能似乎与原始功能稍有不同,该功能无法通过我的测试。

however, the restored function seems slightly different from the original one, which fails my test.

这是示例代码:

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

您是否知道如何将序列化/反序列化提高到消除这种失真?

Do you have any idea how to improve the serialization/deserialization to eliminate this distortion?

还是对相等性测试部分有任何建议?

Or any suggestion on equality test part?

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

PS: take account of only simple lambda but not complex closure or ordinary function.

推荐答案

问题是,除非它们都引用相同的变量,否则您无法直接比较函数变量目的。相反,您应该比较 code 对象。

The thing is you can't directly compare function variables unless they both reference the same object. Instead, you should compare code objects.

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

让我们添加一些清晰度。

Let's add some clarity.

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

编辑。我已经使用您的功能和元帅序列化对此进行了测试。工作完美。

Edit. I've tested this with your function and marshal serialization. Works perfectly fine.

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中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆