0

I am trying to load and save objects with this piece of code I get it from a question I asked a week ago: Python: saving and loading objects and using pickle.

The piece of code is this:

class Fruits: pass

banana = Fruits()    
banana.color = 'yellow'     
banana.value = 30

import pickle

filehandler = open("Fruits.obj","wb")    
pickle.dump(banana,filehandler)    
filehandler.close()

file = open("Fruits.obj",'rb')    
object_file = pickle.load(file)    
file.close()

print(object_file.color, object_file.value, sep=', ')

At a first glance the piece of code works well, getting load and see the 'color' and 'value' of the saved object. But, what I pursuit is to close a session, open a new one and load what I save in a past session. I close the session after putting the line filehandler.close() and I open a new one and I put the rest of your code, then after putting object_file = pickle.load(file) I get this error:

Traceback (most recent call last): 
File "<pyshell#5>", line 1, in <module> 
object_file = pickle.load(file) 
File "C:\Python31\lib\pickle.py", line 1365, in load 
encoding=encoding, errors=errors).load() 
AttributeError: 'module' object has no attribute 'Fruits' 

Can anyone explain me what this error message means and telling me how to solve this problem?

Thank so much and happy new year!!

Community
  • 1
  • 1
Peterstone
  • 7,119
  • 14
  • 41
  • 49

2 Answers2

4

Python does not pickle whole classes. Only the names. Therefore you must have the module that contains them saved to a file and importable at the time they are unpickled. Python will then re-import them.

If you run into problems, you may need to define special helper methods, __getstate__ and __setstate__ that are used for pickling.

Keith
  • 42,110
  • 11
  • 57
  • 76
  • 1
    +1, In an other way: the error is raise because pickle wanted to load an instance of the class Fruits and search for the class definition where it was defined, but it didn't find it so it raise the error. – mouad Jan 01 '11 at 12:13
0

So... This is one of the reason pickle is not used by many practitioners who practice OOP - it is horrible for serde. Especially when you shift namespace and the object definition may not be present! So, what is an alternative?

There are two alternatives, dill and cloudpickle. I prefer dill over cloudpickle - but both will work for your case. Install either with pip, then do somehting like

import dill as pickle

or

import cloudpickle as pickle

and then enjoy your lunck.

John Aven
  • 36
  • 3