Python3:如何从pickle加载中检查lambda源?

时间:2018-04-09 08:09:06

标签: python pickle

有没有办法可以看到加载的cloudpickle对象的python源码? 例如,下面我正在加载对象

In [17]: new_squared = pickle.loads (b'\x80\x02ccloudpickle.cloudpickle\n_fill_function\nq\x00(ccloudpickle.cloudpickle\n_make_skel_func\nq\x01ccloudpickle.cloudpickle\n_builtin_type\nq\x02X\x08\x00\x00\x00CodeTypeq\x03\x85q\x04Rq\x05(K\x01
...: K\x00K\x01K\x02KCc_codecs\nencode\nq\x06X\x08\x00\x00\x00|\x00\x00d\x01\x00\x13Sq\x07X\x06\x00\x00\x00latin1q\x08\x86q\tRq\nNK\x02\x86q\x0b)X\x01\x00\x00\x00xq\x0c\x85q\rX\x1e\x00\x00\x00<ipython-input-3-fefd3c33c8fb>q\x0eX\x08\x00
...: \x00\x00<lambda>q\x0fK\x01c__builtin__\nbytes\nq\x10)Rq\x11))tq\x12Rq\x13]q\x14}q\x15\x87q\x16Rq\x17}q\x18N}q\x19tR.')
...:
...:

接下来,我将验证它是否有效:

In [18]: new_squared(9)
Out[18]: 81

..确实如此。

如何查看实际的lambda表达式?

如果我尝试使用inspect,我会收到以下错误:

In [19]: import inspect

In [20]: h = inspect.getsource(new_squared)

OSError                                   
Traceback (most recent call last)
<ipython-input-20-62e15704e160> in <module>()
----> 1 h = inspect.getsource(new_squared)

/usr/bin/anaconda/envs/py35/lib/python3.5/inspect.py in getsource(object)
    942     or code object.  The source code is returned as a single string.  An
    943     OSError is raised if the source code cannot be retrieved."""
--> 944     lines, lnum = getsourcelines(object)
    945     return ''.join(lines)
    946

/usr/bin/anaconda/envs/py35/lib/python3.5/inspect.py in getsourcelines(object)
    929     raised if the source code cannot be retrieved."""
    930     object = unwrap(object)
--> 931     lines, lnum = findsource(object)
    932
    933     if ismodule(object):

/usr/bin/anaconda/envs/py35/lib/python3.5/inspect.py in findsource(object)
    760         lines = linecache.getlines(file)
    761     if not lines:
--> 762         raise OSError('could not get source code')
    763
    764     if ismodule(object):

    OSError: could not get source code

0 个答案:

没有答案