How to marshal objects to readable files?

Aaron "Castironpi" Brady castironpi at gmail.com
Sun Sep 14 14:09:52 EDT 2008


On Sep 14, 10:28 am, nielinjie <nielin... at gmail.com> wrote:
> Hi list:
> I just want to marshal objects (instance of custom classes)to a human
> *READABEL *file/string, and also, I want unmarshal it back. in xml
> format or any other format.
> Any advice? Which lib should I use?
> Thanks a lot.

Nielinjie,

There is no generic way; an object can contain a reference to another
object.

You can get started with ob.__dict__ as follows:

>>> class A: pass
...
>>> a= A()
>>> a.b= 0
>>> a.c= 'abc'
>>> a.__dict__
{'c': 'abc', 'b': 0}

But the only way TMK (to my knowledge) to retrieve the contents is
eval, which is very hackish.

The PyYAML package produces the following (continued):

>>> b= A()
>>> b.d= 'efg'
>>> b.e= 1.2
>>> a.d= b
>>> b.parent= a
>>> print yaml.dump( a )
&id001 !!python/object:__main__.A
b: 0
c: abc
d: !!python/object:__main__.A
  d: efg
  e: 1.2
  parent: *id001

>>> print yaml.dump( b )
&id001 !!python/object:__main__.A
d: efg
e: 1.2
parent: !!python/object:__main__.A
  b: 0
  c: abc
  d: *id001
>>> yaml.load( yaml.dump( a ) )
<__main__.A instance at 0x00D098A0>
>>> _.__dict__
{'c': 'abc', 'b': 0, 'd': <__main__.A instance at 0x00D09788>}

It caches IDs to reference circular references, and writes nested
objects in place.  As you can see, you don't need to dump both 'a' and
'b'; 'a' contains 'b' already.  You do need the types of the objects
already living in the same namespace as when you stored them.

If it's not human readable enough for your use, please write an
example of what you want your output to look like.  Abstract is ok.

PyYAML is available at http://pyyaml.org/ .  Download from
http://pyyaml.org/wiki/PyYAML .  I've only skimmed it though.



More information about the Python-list mailing list