Object "dumping"

Derek Thomson dthomson at NOSPAMusers.sf.net
Mon Feb 3 04:09:00 EST 2003


Tyler Eaves wrote:
> try something like:
> 
> attribs = dir(object)
> attribs.sort()
> for i in attribs:
>     exec('print str(object.'+i+')')

Good idea.

I tried this out, and then got carried away and made it recurse through 
the object tree (it stops if it detects an object that it has seen 
before, so it will never recurse forever). It also indents the (attr, 
value) pairs as it recurses so it's vaguely readable.

I also used 'getattr' instead of 'exec', as it should be faster, and is 
more understandable - to me anyway!

This will do what I want, but clearly this could be extended to handle 
sequences and hashes, too.

Thanks for the help!

#!/usr/bin/env python

import types

class Dumper:

     indent = "\t"

     def __init__(self):

         # We're going to keep references to objects that we've already
         # seen in a list
         self.seen = []

         return

     def dump(self, obj):
         self.dump_rec(obj, 0)

     def dump_rec(self, obj, level):

         attributes = dir(obj)
         attributes.sort()

         self.seen.append(obj)

         for attribute in attributes:

             value = getattr(obj, attribute)
             print Dumper.indent * level, attribute, ':', value

             if (type(value) == types.InstanceType and
                 not value in self.seen):
                 self.dump_rec(value, level+1)

         return





More information about the Python-list mailing list