I am trying to make a fast copy of a class instance. cPickle.loads(cPickle.dumps(),-1)
works fine, almost 5 times faster than copy.deepcopy
, but I read that ujson
is much faster than cPickle
. I could not get ujson to work with a custom class, is it possible to do so?
example:
import cPickle as pickle
import ujson
class AClass(object):
def __init__(self):
print('init')
self.v = 10
self.z = [2,3,4]
self._zdict = dict(zip(self.z,self.z))
a = AClass()
a
#<__main__.AClass at 0x118b1d390>
# does not work with ujson
ua = ujson.dumps(a)
au = ujson.loads(ua)
au
#{u'v': 10, u'z': [2, 3, 4]}
# but works with pickle
pa = pickle.dumps(a)
ap = pickle.loads(pa)
ap
#<__main__.AClass at 0x117460190>
An idea is to define your own protocole, base of the concept described for pickle. Define a
__getstate__
and__setsatte__
instance in your class:Then, you can define a
save()
and aload()
function like this:Simple usage (using a
StringIO
here instead of a classic file):