Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- import types
- import pprint
- from pickle import Unpickler
- pp = pprint.PrettyPrinter(indent=4)
- class GenericClass(object):
- def __new__(cls, *p, **k):
- inst = object.__new__(cls)
- inst.args = ()
- inst.kwargs = {}
- inst.to_dict_called = False
- inst.state = {}
- return inst
- def __init__(self, *args, **kwargs):
- self.args = args
- self.kwargs = kwargs
- def __setstate__(self, state):
- self.state = state
- def to_dict(self):
- if getattr(self, 'to_dict_called', False):
- return {'circle': True}
- self.to_dict_called = True
- d = {'args': self.args, 'kwargs': self.kwargs}
- if not isinstance(self.state, dict):
- return {'state': self.state}
- for k, v in self.state.iteritems():
- if isinstance(v, GenericClass):
- d[k] = v.to_dict()
- else:
- d[k] = v
- return d
- def __repr__(self):
- return str(self.args)
- class GenericUnpickler(Unpickler):
- def find_class(self, module, name):
- # Subclasses may override this
- return GenericClass
- with open("sample.pickle", "rb") as f :
- myobj = GenericUnpickler(f).load()
- pp.pprint(myobj.to_dict())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement