unpickle_manything.py

Send to Kindle
home » snippets » python » pickle » unpickle_manything.py


import cStringIO as StringIO
import cPickle

# Manything Unpickler stuff.

class DictObject(object):
  """Replace this with whatever class you want to use in place of the actual
  classes in the pickle stream."""
  def __new__(cls, *args, **kwargs): return object.__new__(cls)
  def __str__(self): return str(self.__dict__)

def unpickle_manything(stream):
  unpickler = cPickle.Unpickler(stream)
  unpickler.find_global = lambda module_name, class_name: DictObject
  return unpickler.load()


# Here, we pickle and unpickle a few things using unpickle_manything
# to test it out.

class Foo(object):
  """Random class we want to unpickle."""
  def __init__(self, **kwargs): self.__dict__.update(kwargs)
  def __str__(self): return str(self.__dict__)

def test_manything_unpickle(obj):
  print "Pickling: %s of type %s" % (obj, type(obj))
  pickled_stream = StringIO.StringIO(cPickle.dumps(obj))
  clone = unpickle_manything(pickled_stream)
  print "Unpickled: %s of type %s\n" % (clone, type(clone))

# Test some objects.
for obj in (
            1,
            True,
            [1,2,3],
            "string",
            Foo(greeting="hello, world")):
  test_manything_unpickle(obj)