Using the example
def foo(a):
def bar(b):
return a+b
return bar
d = {1:foo(1), 2:foo(2)}
It appears that pickle module will not work with a function not defined at the module scope, so pickling ‘d’ will not work. Is there another pickling mechanism available that I should consider?
I’m afraid that you can’t pickle nested functions.
The
picklemodule serializes functions by name. That is, if you have a functionmyfuncin a modulemymoduleit simply saves the namemymodule.myfuncand looks it up again when unserializing. (This is an important security and compatibility issue, as it guarantees that the unserializing code uses its own definition for the function, rather than the original definition which might be compromised or obsolete.)Alas,
picklecan’t do that with nested functions, because there’s no way to directly address them by name. Yourbarfunction, for instance, can’t be accessed from outside offoo.If you need a serializable object that works like a function, you can instead make a class with a
__call__method:This works just like the nested functions in the question, and should pose no problem to
pickle. Do be aware though, that you’ll need to have the same class definition available when you unserialize afooinstance.