Skip to content

Instantly share code, notes, and snippets.

@emperorcezar
Created August 24, 2017 04:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emperorcezar/46e627f382a5e8949f49d90e1f3ad8d8 to your computer and use it in GitHub Desktop.
Save emperorcezar/46e627f382a5e8949f49d90e1f3ad8d8 to your computer and use it in GitHub Desktop.
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())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment