saving a complex object to disc

Josiah Carlson jcarlson at uci.edu
Sun Oct 24 01:56:49 EDT 2004


raragues at hotmail.com (ramon) wrote:
> 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




More information about the Python-list mailing list