Pickling C objects

Stuart Reynolds S.I.Reynolds at cs.bham.ac.uk
Wed Jul 14 09:47:08 EDT 1999


Fred L. Drake wrote:
> 
> Stuart Reynolds writes:
>  > I'm writing some new Python classes with a C implementation. How do you
>  > make a C object pickleable?
> 
>   Take a look at the source for the parser module in the standard
> source distribution; it uses the copy_reg module to register a
> mechanism to support pickling.  It worked when I wrote it, but I
> haven't tried it lately.  (A good candidate for a regression test!)
> 

Groovy. You don't even need to worry about whether the object is written
partly in C as long as you can recreate the C bits from Python (e.g. via
the constructor call).


---------

import copy_reg


class Saveable:
    def __init__(self, a, b):
	self.a = a
	self.b = b

    def __repr__(self):
	"""Returns a string which may be evaluated
	in order to reconstruct this object.
	"""
	ser = self.__class__.__name__      \
	      +'('                         \
 	      +   repr(self.a) + ','       \
	      +   repr(self.b)             \
	      +')'
	return ser




def __Saveablesaver__(object):
    """Returns a serialised version of object"""
    return repr(object)


def __Saveableloader__(serialised):
    """ Unserialised `serialised' and return
    a new Saveable object """
    return eval(serialised)





#Register the Saveable pickling functions
copy_reg.pickle( Saveable, __Saveablesaver__, __Saveableloader__ )



if __name__ == '__main__':
    """ Test the serialisation of Saveable  """
    #import pickle
    import cPickle
    pickle = cPickle

    sm = Saveable( 1, ['a','b',(4,5,6)] )
    
    #View the serialised form
    print 'Saving: ', repr(sm)


    pickle.dump( sm, open('deleteme','w') )
    obj = pickle.load( open('deleteme','r') )

    print 'Loaded: ', repr(obj)

------
Should output the following:

Saving:  Saveable(1,['a', 'b', (4, 5, 6)])
Loaded:  Saveable(1,['a', 'b', (4, 5, 6)])




More information about the Python-list mailing list