pickle python Class instance

pickle, python

Solution

Instead of inherting from "nothing", inherit from "object" - this way your class will no longer be a "Class Instance" - it will be a proper instance of a new-style class, and as such, be "pickeable"

In other words, just try changing this line:

class boardClass():

to this:

class boardClass(object):

update: This answer is from Python 2 era - and explicitly inheritng from object was needed there. In Python 3 it is no longer the case: inheritance from `object` is automatic, and if pickle is failing it is for some other reason.

Problem

I have a simple class to just store data that's associated to a circuit board like this : ``` class boardClass(): def __init__(self,boardName): self.__name=boardName self.__boardMappings= {boardName:{ 'FastMode': {'CPU_A':{'mipi':[], 'gpen':[]}, 'CPU_B':{'mipi':[], 'gpen':[]} 'SlowMode': {'CPU_A':{'mipi':[], 'gpen':[]}, 'CPU_B':{'mipi':[], 'gpen':[]} } } } def setMode(self, board, mode, cpu,mipi,gpen): self.__boardMappings[board][mode][cpu]['mipi']=mipi self.__boardMappings[board][mode][cpu]['gpen']=gpen def getName(self): return self.__name ``` I use pickle in another class to store the `boardClass` data in file and later read them: ``` def onSave(self,boardName): board=boardClass.boardClass(boardName) name=boardName+".brd" file=open(name,"wb") pickle.dump(board,file) loadedBoard= pickle.load( open( file, "rb" )) print "Loaded board name is : ",loadedBoard.getName() ``` When I call `onSave()` method to pickle the boardClass, it gives several errors ending with this at end: ``` File "C:\Python27\lib\copy_reg.py", line 70, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle PySwigObject objects ``` This boardClass is very simple container. Why can't it be pickled?

Original source

Related problems