Create a gist now

Instantly share code, notes, and snippets.

Pickling class definitions for IPython.parallel
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)
ogrisel commented Jan 6, 2013

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.

minrk commented Jan 6, 2013

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 :)

ogrisel commented Jan 7, 2013

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment