public
Last active

Pickling class definitions for IPython.parallel

  • Download Gist
class_def_pickling.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
import inspect
from pickle import loads, dumps
from IPython.utils import pickleutil
 
 
def class_dumps(cls):
canned_dict = pickleutil.canDict(
dict((k, v) for k, v in cls.__dict__.items()
if k not in ('__weakref__', '__dict__')))
parents = tuple(cls.mro())
# TODO: recursively call class_dumps on parents that can from the same
# module as the module of cls
return dumps((cls.__name__, parents, canned_dict))
 
 
def class_loads(cls_str):
name, parents, canned_dict = loads(cls_str)
return type(name, parents, pickleutil.uncanDict(canned_dict))
 
 
# Let's define some classes to copy and %paste into an interactive ipython
# session:
"""
 
class AClass(object):
 
def __init__(self, a):
self.a = a
 
def a_method(self, b):
return self.a + b
 
 
class BClass(AClass):
 
def b_method(self, b):
return self.a_method(b) * 2
 
 
AClassClone = class_loads(class_dumps(AClass))
BClassClone = class_loads(class_dumps(BClass))
b = BClassClone(3)
b.b_method(4)
 
"""

This trick could be contributed to the IPython.utils.pickleutil module as a new method canClass and uncanClass (or better as can_class and uncan_class to respect PEP8 :) + a CannedClass class.

Have you looked at current pickleutil? I rewrote it for 0.14, so it's no longer Twisted-style. Anything camelCase was written during the Twisted days, where it is better to be internally consistent, and thus follow Twisted, than use pep8 inconsistently. That said, I don't have much respect for pep8 :)

Indeed, I was still running 0.13. I have now switched to the git version.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.