""" Demonstrate a problem with user-defined exceptions raised during unpickling that cPickle tries to extend with additional exception information """ import cPickle as pickler import logging class MyException(Exception): """Exception class with restrictive __init__ arguments""" def __init__(self, message): self.message = message def __str__(self): return self.message class BadReduce(object): """Object that raises an exception on unpickling""" def __init__(self, arg): if arg == 1123: exception = MyException('BadReduce init failed') # Demonstrate that we successfully constructed the exception logging.info('Raising exception "%s"', exception) raise exception def __reduce__(self): return BadReduce, (1123,), None, None, None def main(): logging.basicConfig(level=logging.NOTSET) logging.info('Creating BadReduce object') b1 = BadReduce(0) logging.info('Pickling') s1 = pickler.dumps(b1, pickler.HIGHEST_PROTOCOL) logging.info('Unpickling') try: pickler.loads(s1) except MyException as e: logging.info('Got MyException "%s"', e) logging.info('Done') if __name__ == '__main__': main()