0

when i use pickle package to serialize a dict object for example, i can load it in another context without problem. but it's not the case for functions unless i import it again as explained here (i don't know if it's feasible in case of functions defined inside notebooks). But why this behaviour?, how function object is different from dict object?

example:

open notebook A, run the following:

def func(x):
   return x**2
with open("myfile", "wb") as f:
    pickle.dump(func,f)

open notebook B, run the following:

with open("myfile", "rb") as f:
    func = pickle.load(f)

this would return

AttributeError: Can't get attribute 'func' on <module '__main__'>
Kaoutar
  • 345
  • 2
  • 10
  • Indeed, [that is the documented behavior](https://docs.python.org/3/library/pickle.html#what-can-be-pickled-and-unpickled), although I'm confident that what the OP wants _can_ be done, I just don't know how. – rodrigo Dec 16 '22 at 14:12
  • Unpickling functions is not possible using pickle because pickle is designed to store data in a serialized format, and functions are not serializable. – Kylar Dec 16 '22 at 14:18
  • @rodrigo, you're right, i'v read the same thing about the save method of pytorch models – Kaoutar Dec 16 '22 at 14:18
  • @jasonharper, can you please elaborate more. – Kaoutar Dec 16 '22 at 14:19
  • Actually try this. `func = pickle.load(f, "rb"))` – Kylar Dec 16 '22 at 14:24
  • @Kylar, i think i should read more about serialization – Kaoutar Dec 16 '22 at 14:27

0 Answers0