Using dill
pickling of lambda functions work fine in Python 2, but not in Python 3, is there any alternative?
Python 3:
import dill
import pickle
pickle.dumps(lambda x: x**2)
pickle.PicklingError: Can't pickle at 0x104e97840>: attribute lookup on main failed
Python 2.7:
import dill
import pickle
pickle.dumps(lambda x: x**2)
cdill.dill\n_create_function\np0\n(cdill.dill\n_load_type\np1\n(S'CodeType'\np2\ntp3\nRp4\n(I1\nI1\nI2\nI67\nS'|\x00\x00d\x01\x00\x13S'\np5\n(NI2\ntp6\n(t(S'x'\np7\ntp8\nS''\np9\nS''\np10\nI1\nS''\np11\n(t(ttp12\nRp13\nc__main__\n__dict__\ng10\nNN(dp14\ntp15\nRp16\n.
Seems like in python 2, dill replaces
pickle
when you import. In python 3, you have to use dill directly instead.This works in python 3.5:
Alternatively you can also
import dill as pickle