saving a complex object to disc

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • ramon

    #1

    saving a complex object to disc

    Hi!

    I have a fairly complex object (with other objects as attributes
    (which in turn, have other objects as attributes), methods, etc) and I
    would like to save it to the disc so I can load it in the future. I've
    been reading about pyckle but I am not sure if that's what I need,
    since apparently one has to define exactly what he wants to save and
    how (and gives errors if the object has methods). I'd like to save the
    object as it is, and be able to get it from the file afterwards...

    Can somebody point me into the right direction to achieve this?

    Thanks,

    Ramon
  • Josiah Carlson

    #2
    Re: saving a complex object to disc


    raragues@hotmai l.com (ramon) wrote:[color=blue]
    > I have a fairly complex object (with other objects as attributes
    > (which in turn, have other objects as attributes), methods, etc) and I
    > would like to save it to the disc so I can load it in the future. I've
    > been reading about pyckle but I am not sure if that's what I need,
    > since apparently one has to define exactly what he wants to save and
    > how (and gives errors if the object has methods). I'd like to save the
    > object as it is, and be able to get it from the file afterwards...
    >
    > Can somebody point me into the right direction to achieve this?[/color]

    If you are saving and loading it within equivalent namespaces (same
    imports for the modules that contain the object description, etc.),
    pickle would likely be sufficient. It works best when there is pure
    built-in types, but it usually ends up just pickling the __dict__
    attribute of user-defined classes (which is usually sufficient, unless
    you do things with properties...).

    Really there is only one way to find out: try it!


    import cPickle

    st = cPickle.dumps(t est_obj)
    out_obj = cPickle.loads(s t)

    If you can pragmatically compare test_obj and out_obj to determine if
    they are, in fact, equivalent, then your problem is solved.

    One thing to remember when writing to/from pickle files; always open the
    files in binary (modes 'rb' or 'wb'). It guarantees that you won't get
    borked by line endings, etc.

    - Josiah

    Comment

    Working...