Last active
December 10, 2015 17:48
-
-
Save ogrisel/4470212 to your computer and use it in GitHub Desktop.
Pickling class definitions for IPython.parallel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
""" |
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This trick could be contributed to the
IPython.utils.pickleutil
module as a new methodcanClass
anduncanClass
(or better ascan_class
anduncan_class
to respect PEP8 :) + aCannedClass
class.