Python的代码编组是否可逆?

时间:2017-08-16 14:07:34

标签: python marshalling python-3.6

考虑以下脚本:

from marshal import dumps, loads


def square_fn(x):
    return x * x


def test_serialize_marshal():
    code_string = dumps(square_fn.__code__)
    code_string1 = dumps(loads(code_string))
    assert code_string == code_string1

使用pytest在Python 3.6中运行。

此测试在我的计算机上失败。为什么会这样?

我试图以一种方式序列化Python函数,我可以从它的序列化表示中测试该函数是否相同......这个测试表明这不是编组转储/加载的情况。

修改

有趣的是,这个测试通过了:

def test_serialize_marshal2():
    import types

    code = dumps(square_fn.__code__)
    ff = types.FunctionType(loads(code), globals())

    assert square_fn.__code__ == ff.__code__

这是this answer tests。但是,我不希望Python对象的相等,而是字符串。

0 个答案:

没有答案