I am afraid that you cannot reveal nested functions.
The pickle module serializes functions by name. That is, if you have the myfunc function in the mymodule module, it simply saves the name mymodule.myfunc and looks for it again when not serializing. (This is an important security and compatibility issue, as it ensures that non-serializing code uses its own definition for the function, not the original definition, which may be compromised or deprecated.)
Alas, pickle cannot do this with nested functions, because there is no way to directly access them by name. For example, your bar function is not accessible from outside foo .
If you need a serializable object that works as a function, you can instead create a class using the __call__ method:
class foo(object): def __init__(self, a): self.a = a def __call__(self, b):
This works just like the nested functions in the question, and should not present any problems for pickle . However, keep in mind that you need to have the same class definition if you are not serializing an instance of foo .
source share