pprinting objects

John Machin sjmachin at lexicon.net
Sat Dec 8 05:48:44 EST 2007


On Dec 8, 9:16 pm, Donn Ingle <donn.in... at gmail.com> wrote:
> Hi,
>  Is there a way to get a dump of the insides of an object? I thought pprint
> would do it. If I had a class like this:
>
> class t:
>  def __init__(self):
>   self.x=1
>   self.y=2
>   self.obj = SomeOtherObj()
>
> Then it could display it as:
>
> <class> t,
>  x,1,
>  y,2,
>  obj,<class SomeOtherObj>
>
> Or something like that -- a complete output of the object really, with
> id()'s and so forth.
>
> \d

AFAIK you have to roll your own. Here is a very rudimentary example:

C:\junk>type dumpobj.py
class MixDump(object):
    def dump(self):
        print "Dump of", self.__class__.__name__, 'instance'
        for attr, value in sorted(self.__dict__.iteritems()):
            print attr, repr(value)

class T(MixDump):
    def __init__(self):
        self.x=1
        self.y=2
        self.obj = list()
    def amethod(self):
        pass

class U(MixDump):
    def __init__(self):
        self.f = 'foo'
        self.yorick = 'y'
        self.bananas = None

t = T()
t.dump()
u = U()
u.dump()

C:\junk>dumpobj.py
Dump of T instance
obj []
x 1
y 2
Dump of U instance
bananas None
f 'foo'
yorick 'y'

HTH,
John




More information about the Python-list mailing list