Pyhon Pickle not working for custom classes in IPython

Hi,

I want to pickle a custom class to attach as a string to Rhino objects for later reuse.
However, I cannot seem to cet ©Pickle to work from Rhino, where is does work in ‘regular’ python.
Could anyone enlighten me in how to deal with this?

Code like this will raise error:

Message: No module named __main__

import cPickle

class MyClass():
    pass

def main():
    pick_test = MyClass()
    print 'pick_test ',pick_test
    
    pick_string = cPickle.dumps(pick_test,0) #create pickle string
    load_test = cPickle.loads(pick_string) #load pickle string
    
    print 'load_test',load_test

if __name__ == '__main__':
    main()

Thanks
-Willem

Your example isn’t a typical ‘pickling’ example. Unpickling an instance involves defining its class by loading the appropriate module (if this module is not already loaded).

For example, define you class in a separate module.

# test.py
print "Defining the class Test"
class Test:
    def __init__(self, x):
        self.data = "I am Test '%d'" % x

Then test your class.

# pickle_tester.py
def main():
    import cPickle
    from test import *
    
    pick_test = Test(123)
    print 'pick_test',pick_test
    print 'pick_test',pick_test.data
    print ' '
    
    pick_string = cPickle.dumps(pick_test,0) #create pickle string
    print pick_string
    print ' '
    
    load_test = cPickle.loads(pick_string) #load pickle string
    
    print 'load_test',load_test
    print 'load_test',load_test.data
    print ' '

if __name__ == '__main__':
    main()

I’ve been working on basically the same thing as a way to get data-structure persistence between script executions. Word to the wise, make sure all the data you intend to pickle is in instance variables rather than class variables or you’re going to have a bad time. Also, cPickle doesn’t seem to be very friendly towards classes of the Rhino.Geometry persuasion. I’ll keep trying but I think this might be because they’re defined in RhinoCommon.