saving a complex object to disc

R

ramon

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
 
J

Josiah Carlson

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?

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(test_obj)
out_obj = cPickle.loads(st)

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top