pickling new-style extension types: examples?

Stefan Quandt squan at web.de
Sat Apr 5 08:44:20 CEST 2003

Maciej Kalisiak <mac at die.spammer.die.dgp.toronto.edu> wrote in message news:<slrnb8scn8.d6f.mac at mac.dgp.toronto.edu>...
> I've implemented a new extension type in C, and am now attempting to make it
> picklable, with little success.  Can someone point out any online examples of
> doing this, or even post some code snippets?  Ideally I would want to implement
> the pickling functionality in C, but will settle for a Python class wrapper
> around the extension type, if necessary.  Either the __reduce__ protocol, or
> using the "copy_reg" module will do.


To pickle an extension type you need 
 - a mechanism to "serialize" it (convert to a string) and
 - one to reconstruct it from a string.
Then you write a Python wrapper class where you implement the special
__getstate__() and __setstate()__ which are called by the pickle
modules dump()/load():

class Wrapper( object ):
  def __init__( self ): self.c_object = CExtensionType( whatever )
  def __getstate__( self ):
    # Replace extension type instance by string converted version
    self.c_object_str = serialize( self.c_object )
    del self.c_object
    return self.__dict__
  def __setstate__( self, state ):	# state is a dict
    state[ c_object ] = CExtensionType( state.c_cobject_str ) #
Reconstruct from string
    del state[ c_object ] # delete string representation
    self.__dict__.update( state )

More information about the Python-list mailing list