The importance of printable objects

November 9, 2006

I have a small defect in the Python code I produce: I rarely bother to make my classes printable or to give them a repr(). Most of the classes will never be printed, and the default repr value is good enough to distinguish two instances from each other.

But this is a mistake, nicely illustrated by my grump about assert's weakness as a debugging tool. Objects having a useful string value makes it much easier to dump out information about the state of things when a problem comes up. You can cope without it and I usually have, but it's working harder than you should have to.

While the convention of making the repr value something that can be used to reproduce the object is nice, don't let it stop you from having a repr value of some sort. You're not really losing anything when the alternative is a '< object at 0xdeadbeef>' thing, although you probably should make sure that you can still tell apart two instances that happen to have identical values.

(You can do without this if your objects have both an equality operator and a hash operator. With just an equality operator, you may someday wind up trying to figure out why an object is not found as the key in a dictionary when you can see that it's right there darnit.)

The default repr function for instances is more or less equivalent to:

"<%s.%s at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, id(self))

The one wart is that id() should really return a Python long that's always positive, instead of an integer that's sometimes negative on 32-bit platforms. On 32-bit platforms you can mask id() with 0xffffffff to get the right value and avoid annoying warnings, but of course this blows up on 64-bit platforms.

Written on 09 November 2006.
« Link: Pumas on Hoverbikes
A fundamental problem with challenge/response anti-spam systems »

Page tools: View Source, Add Comment.
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Thu Nov 9 00:09:05 2006
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.