Advertisement
Guest User

Untitled

a guest
Aug 24th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. import sys
  2. import types
  3. import pprint
  4.  
  5. from pickle import Unpickler
  6.  
  7. pp = pprint.PrettyPrinter(indent=4)
  8.  
  9. class GenericClass(object):
  10. def __new__(cls, *p, **k):
  11. inst = object.__new__(cls)
  12. inst.args = ()
  13. inst.kwargs = {}
  14. inst.to_dict_called = False
  15. inst.state = {}
  16. return inst
  17.  
  18. def __init__(self, *args, **kwargs):
  19. self.args = args
  20. self.kwargs = kwargs
  21.  
  22. def __setstate__(self, state):
  23. self.state = state
  24.  
  25. def to_dict(self):
  26. if getattr(self, 'to_dict_called', False):
  27. return {'circle': True}
  28. self.to_dict_called = True
  29. d = {'args': self.args, 'kwargs': self.kwargs}
  30. if not isinstance(self.state, dict):
  31. return {'state': self.state}
  32. for k, v in self.state.iteritems():
  33. if isinstance(v, GenericClass):
  34. d[k] = v.to_dict()
  35. else:
  36. d[k] = v
  37. return d
  38.  
  39. def __repr__(self):
  40. return str(self.args)
  41.  
  42. class GenericUnpickler(Unpickler):
  43. def find_class(self, module, name):
  44. # Subclasses may override this
  45. return GenericClass
  46.  
  47. with open("sample.pickle", "rb") as f :
  48. myobj = GenericUnpickler(f).load()
  49.  
  50. pp.pprint(myobj.to_dict())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement