I have to pickle an array of objects like this:
import cPickle as pickle
from numpy import sin, cos, array
tmp = lambda x: sin(x)+cos(x)
test = array([[tmp,tmp],[tmp,tmp]],dtype=object)
pickle.dump( test, open('test.lambda','w') )
and it gives the following error:
TypeError: can't pickle function objects
Is there a way around that?
You'll have to use an actual function instead, one that is importable (not nested inside another function):
The function object could still be produced by a
lambda
expression, but only if you subsequently give the resulting function object the same name:because
pickle
stores only the module and name for a function object; in the above example,tmp.__module__
andtmp.__name__
now point right back at the location where the same object can be found again when unpickling.The built-in pickle module is unable to serialize several kinds of python objects (including lambda functions, nested functions, and functions defined at the command line).
The picloud package includes a more robust pickler, that can pickle lambda functions.
PiCloud-serialized objects can be de-serialized using the normal pickle/cPickle
load
andloads
functions.Dill also provides similar functionality
There is another solution: define you functions as strings, pickle/un-pickle then use eval, ex:
This could be more convenient for other solutions because the pickled representation would be completely self contained without having to use external dependencies.