Object "dumping"

Andrew Bennetts andrew-pythonlist at puzzling.org
Mon Feb 3 05:02:58 EST 2003


On Mon, Feb 03, 2003 at 07:25:30PM +1000, Derek Thomson wrote:
> Hi Andrew,
> 
> Andrew Bennetts wrote:
> > On Mon, Feb 03, 2003 at 11:47:38AM +1000, Derek Thomson wrote:
> >>
> >>I know Python has pprint, but that stops when it encounters an object
> >>ie. it only dumps sequences and hashes, which is less than what I want.
> >
> >
> > The problem is harder than it seems... simply recursively printing the
> > objects and their contents won't work for cyclic objects, so for many data
> > structures, you *need* something that can cope with this, like pickle.
> 
> No, I'm aware of this issue. Perl's Data::Dumper just deals with it :)

Yes, but I don't know (much) Perl, so I didn't know what it could do, so
saying "I want Data::Dumper for Python" didn't help me much :)

[..snip..]
> > There are other pickle alternatives too, like an XMLPickle, iirc.
> 
> Yes, but I need human readable, not XML! :)
> 
> I guess twisted.spread.jelly is an option, but I'd prefer it if the output
> were just Python - then there's no need to learn a new notation.
> 
> Anyway, thanks heaps.

Well...

There's also twisted.persisted.aot, which does serialise to Python code that
will reconstruct the objects.  But Jelly's notation is really quite
readable:

    >>> from twisted.spread import jelly
    >>> class C:
    ...     pass
    ... 
    >>> class D: 
    ...     pass
    ... 
    >>> c = C()
    >>> c.d = D()
    >>> c.foo = 'bar'
    >>> c.d.baz = 'quux'
    >>> c.x = 1
    >>> jelly.jelly(c)
    ['__main__.C', ['dictionary', ['x', 1], ['foo', 'bar'], ['d', ['__main__.D', ['dictionary', ['baz', 'quux']]]]]]

Ok, that's a bit hard to follow on one line like that... so lets pprint it:

    >>> from pprint import pprint
    >>> pprint(jelly.jelly(c))
    ['__main__.C',
     ['dictionary',
      ['x', 1],
      ['foo', 'bar'],
      ['d', ['__main__.D', ['dictionary', ['baz', 'quux']]]]]]

For comparison, t.p.aot does this:

    >>> from twisted.persisted import aot
    >>> print aot.jellyToSource(c)
    app=Instance('__main__.C',
      d=Instance('__main__.D',
        baz='quux',),
      foo='bar',
      x=1,)

-Andrew.






More information about the Python-list mailing list