Skip to content

Instantly share code, notes, and snippets.

@luoq
Last active November 10, 2017 02:01
Show Gist options
  • Save luoq/703ec045827caf5a504ff97376db9c3e to your computer and use it in GitHub Desktop.
Save luoq/703ec045827caf5a504ff97376db9c3e to your computer and use it in GitHub Desktop.

test pickle for instance method

pickling instance method failed for python2

------
cmath
sin
p0
.
------
(i__main__
C
p0
(dp1
b.
------
Traceback (most recent call last):
File "test.py", line 17, in <module>
test()
File "test.py", line 14, in test
print(pickle.dumps(c.f))
File "/usr/lib/python2.7/pickle.py", line 1380, in dumps
Pickler(file, protocol).dump(obj)
File "/usr/lib/python2.7/pickle.py", line 224, in dump
self.save(obj)
File "/usr/lib/python2.7/pickle.py", line 306, in save
rv = reduce(self.proto)
File "/usr/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects
------
b'\x80\x03cmath\nsin\nq\x00.'
------
b'\x80\x03c__main__\nC\nq\x00)\x81q\x01.'
------
b'\x80\x03cbuiltins\ngetattr\nq\x00c__main__\nC\nq\x01)\x81q\x02X\x01\x00\x00\x00fq\x03\x86q\x04Rq\x05.'
class C:
def f(x):
return x+1
def test():
import pickle
import math
print('------')
print(pickle.dumps(math.sin))
c = C()
print('------')
print(pickle.dumps(c))
print('------')
print(pickle.dumps(c.f))
if __name__ == '__main__':
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment