pprinting objects

D

Donn Ingle

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
 
J

John Machin

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
 
M

Martin Blume

Is there a way to get a dump of the insides of an object?
I thought pprint would do it.
print would actually like to do it if you told it how to do it.
print actually does it, but takes a default implementation if
you do not override __repr__ or __str__.
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.
Define a __repr__ or __str__ method for the class:

class t:
def __init__(self):
self.x=1
self.y=2
self.obj = SomeOtherObj()

def __repr__(self):
s = "<class> %s\n x,%d\n y,%d\n obj,<class %s>" \
% (self.__class__, self.x, self.y, self.obj.__class__)
return s

a_t = t()
print "a t obj: %s" % (a_t)


a t obj: <class> __main__.t
x,1
y,2
obj,<class __main__.SomeOtherObj>


HTH
Martin
 
D

Donn Ingle

Define a __repr__ or __str__ method for the class
Yes, then I could include the code John Machin suggested in there:

for attr, value in sorted(self.__dict__.iteritems()): blah

That will do nicely. Thanks all.

\d
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top