On Oct 17, 3:42 pm, Andrew Mathas <andrew.mat...@gmail.com> wrote:
> One of the things that I like about sage is python, but what I like least
> about it is documentation, which is often missing or inadequate.

And which should then be improved, preferably by the person who has
just identified in what way the documentation is deficient!
Pickle is a python thing, so for a large part you should look in the
python documentation:

http://docs.python.org/library/pickle.html#what-can-be-pickled-and-unpickled

In particular, one of the hints there would have set you on the right
track:

>Similarly, when class instances are pickled, their class’s code and data are 
>not pickled along with them. Only the instance data are pickled. This is done 
>on purpose, so you can fix bugs in a class or add methods to the class and 
>still load objects that were created with an earlier version of the class. If 
>you plan to have long-lived objects that will see many versions of a class, it 
>may be worthwhile to put a version number in the objects so that suitable 
>conversions can be made by the class’s __setstate__() method.

On the other hand, I didn't know about register_unpickle_override. I
think that's a sage thing, so that might be a place to put better
pointers. Perhaps a less trivial example?

from sage.structure.sage_object import register_unpickle_override
class A(object):
    def __init__(self,value):
        self.original_attribute = value
    def __repr__(self):
        return "B(%s) instance"%self.new_attribute
class B(object):
    def __init__(self,value):
        self.new_attribute = value
    def __setstate__(self,args):
        try:
            self.new_attribute = args['new_attribute']
        except KeyError:
            #must be an old pickle
            self.new_attribute = args['original_attribute']
    def __repr__(self):
        return "B(%s) instance"%self.new_attribute

sage: a = A(10)
sage: register_unpickle_override('__main__', 'A', B)
sage: b = B(20)
sage: an = loads(dumps(a))
sage: print an
B(10) instance
sage: bn = loads(dumps(b))
B(20) instance
sage: print bn

Someone should feel free to work this into appropriate doc. I thought
this was pretty discoverable already :-).

By the way, Andrew, 4 hours for learning how python's pickle protocol
works isn't so bad :-).

Cheers,

Nils

-- 
You received this message because you are subscribed to the Google Groups 
"sage-devel" group.
To post to this group, send email to sage-devel@googlegroups.com.
To unsubscribe from this group, send email to 
sage-devel+unsubscr...@googlegroups.com.
Visit this group at http://groups.google.com/group/sage-devel?hl=en.


Reply via email to