By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,275 Members | 1,745 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,275 IT Pros & Developers. It's quick & easy.

Rich __repr__

P: n/a
Howdy all,

The builtin types have __repr__ attributes that return something nice,
that looks like the syntax one would use to create that particular
instance.

The default __repr__ for custom classes show the fully-qualified class
name, and the memory address of the instance.

If I want to implement a __repr__ that's reasonably "nice" to the
programmer, what's the Right Way? Are there recipes I should look at?

--
\ "For certain people, after fifty, litigation takes the place of |
`\ sex." -- Gore Vidal |
_o__) |
Ben Finney
Oct 31 '05 #1
Share this Question
Share on Google+
7 Replies


P: n/a
Ben Finney <bi****************@benfinney.id.au> wrote:
If I want to implement a __repr__ that's reasonably "nice" to the
programmer, what's the Right Way? Are there recipes I should look
at?


As a (carefully selected) example from the code I'm writing:

import lib.attribute
m = lib.attribute.Human_Sex("male")
m Human_Sex(name='male') isinstance(m, basestring) True print m

male

Thus, a Human_Sex instance is a string, and that's how it prints
(because of the __str__ attribute of the 'str' type). But since there
are potentially other things to know about a Human_Sex instance, the
__repr__ is overridden to give an idealised constructor call for the
instance.

class Human_Sex(str):
def __repr__(self):
repr_str = "%s(name=%s)" % (
self.__class__.__name__,
str.__repr__(self)
)
return repr_str

def __init__(self, name):
str.__init__(name)
# [... other initialisation for this class ...]

I've simplified somewhat; Human_Sex is actually just one possible
attribute being implemented, and the above methods actually come from
a superclass. I'm looking for how to do this in general, and this is a
simple enough example of what I want.

Is this __repr__ implementation too complex? Too simple? Limited in
some way? Confusingly non-standard?

--
\ "Laurie got offended that I used the word 'puke.' But to me, |
`\ that's what her dinner tasted like." -- Jack Handey |
_o__) |
Ben Finney
Oct 31 '05 #2

P: n/a
Ben Finney wrote:
The builtin types have __repr__ attributes that return something nice,
that looks like the syntax one would use to create that particular
instance.

The default __repr__ for custom classes show the fully-qualified class
name, and the memory address of the instance.

If I want to implement a __repr__ that's reasonably "nice" to the
programmer, what's the Right Way? Are there recipes I should look at?


I tend to use:

def __repr__(self):
if hasattr(self, '__str__'):
return '<%s @ 0x%x (%s)>' % (self.__class__.__name__,
id(self), str(self))
else:
return '<%s @ 0x%x>' % (self.__class__.__name__, id(self))

The general problem here is that the syntax to create an instance may
not (and usually is not, for complex classes) sufficient to recreate the
entire state of an instance. Mutable classes in general compound the
problem, but examples like files and sockets underscore how it's really
impossible to take a snapshot of a class and reproduce it later (even
pickles can't handle these, of course).

If it's a relatively straightforward class where the entire state is
exposed through the constructor, then a friendly repr is possible.
Otherwise, it's not, and trying to otherwise do so may just be confusing.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
It is fatal to enter any war without the will to win it.
-- Douglas MacArthur
Nov 1 '05 #3

P: n/a
In <dk**********@rose.polar.local>, Ben Finney wrote:
class Human_Sex(str):
def __repr__(self):
repr_str = "%s(name=%s)" % (
self.__class__.__name__,
str.__repr__(self)
)
return repr_str


I'm a bit surprised that `Human_Sex` is subclassing `str`.

Ciao,
Marc 'BlackJack' Rintsch
Nov 1 '05 #4

P: n/a
Marc 'BlackJack' Rintsch <bj****@gmx.net> wrote:
In <dk**********@rose.polar.local>, Ben Finney wrote:
class Human_Sex(str):
def __repr__(self):
repr_str = "%s(name=%s)" % (
self.__class__.__name__,
str.__repr__(self)
)
return repr_str


I'm a bit surprised that `Human_Sex` is subclassing `str`.


So far, the "attribute" classes in this application are just
state-encapsulations, so they might as well subclass 'object'. I
subclassed 'str' to get the constructor and __str__ cheaply (in coding
time). The rest of the baggage of 'str' is rather unnecessary, I
suppose.

--
\ "Anything that is too stupid to be spoken is sung." -- Voltaire |
`\ |
_o__) |
Ben Finney
Nov 1 '05 #5

P: n/a
Erik Max Francis <ma*@alcyone.com> wrote:
Ben Finney wrote:
If I want to implement a __repr__ that's reasonably "nice" to the
programmer, what's the Right Way? Are there recipes I should look
at?
I tend to use:

def __repr__(self):
if hasattr(self, '__str__'):
return '<%s @ 0x%x (%s)>' % (self.__class__.__name__,
id(self), str(self))
else:
return '<%s @ 0x%x>' % (self.__class__.__name__, id(self))


Well that just begs the question: what's a good way (or a Right Way,
if that exists) to write a __str__ for a complex class?
If it's a relatively straightforward class where the entire state is
exposed through the constructor, then a friendly repr is possible.
Otherwise, it's not, and trying to otherwise do so may just be
confusing.


"A friendly __repr__" doesn't necessarily mean outputting the full
syntax of a hypothetical constructor for the instance. I'm looking for
ways that people use to have __repr__ communicate things the
programmer will actually want to know, rather than only the qualified
class name and an arbitrary memory address.

It could be done just by hacking __repr__ with whatever things seem
appropriate, in some ad-hoc format. Or, as I'm hoping with this
thread, there may be common practices for outputting object state from
__repr__ that are concise yet easily standardised and/or recognised.

An idempotent __repr__ output seem to be the ideal, but as you say,
there are many classes for which it's impossible. What to do in those
cases? What's the Right Way? What's the common way?

--
\ "There was a point to this story, but it has temporarily |
`\ escaped the chronicler's mind." -- Douglas Adams |
_o__) |
Ben Finney
Nov 1 '05 #6

P: n/a
Ben Finney wrote:
Well that just begs the question: what's a good way (or a Right Way,
if that exists) to write a __str__ for a complex class?
Whatever is most useful for the programmer during debugging.
An idempotent __repr__ output seem to be the ideal, but as you say,
there are many classes for which it's impossible. What to do in those
cases? What's the Right Way? What's the common way?


There is no right way. The common way is to have __str__ print
something meaningful and useful. What that is for a particular class
depends entirely on the circumstances. There is no uniform solution here.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
We must all hang together, or, most assuredly, we will all hang
separately. -- John Hancock
Nov 2 '05 #7

P: n/a
In article <dk**********@rose.polar.local>,
Ben Finney <bi****************@benfinney.id.au> wrote:
Erik Max Francis <ma*@alcyone.com> wrote:
Ben Finney wrote:
If I want to implement a __repr__ that's reasonably "nice" to the
programmer, what's the Right Way? Are there recipes I should look
at?
I tend to use:

def __repr__(self):
if hasattr(self, '__str__'):
return '<%s @ 0x%x (%s)>' % (self.__class__.__name__,
id(self), str(self))
else:
return '<%s @ 0x%x>' % (self.__class__.__name__, id(self))


Well that just begs the question: what's a good way (or a Right Way,
if that exists) to write a __str__ for a complex class?


Well, in my opinion there pretty much isn't a good way. That is,
for any randomly selected complex class, there probably is no
worthwhile string value, hence no good __str__.

This dives off into a certain amount of controversy over what
repr and str are ideally supposed to do, but I think everyone
would agree that if there's an "represent object for programmer"
string value, it's the repr. So the str is presumably not for
the programmer, but rather for the application, and I'm just
saying that for application purposes, not all objects can usefully
be reduced to a string value.

Meanwhile, the code above also raises some questions where str
is already provided. Run it on your subclass-of-str object and
give the object a value of ') hi ('. This is why containers
use repr to render their contents, not str.
It could be done just by hacking __repr__ with whatever things seem
appropriate, in some ad-hoc format. Or, as I'm hoping with this
thread, there may be common practices for outputting object state from
__repr__ that are concise yet easily standardised and/or recognised.


I guess the best I could suggest is to stick with the format
already used by instances (<__main__.C instance at 0x71eb8>)
and augment it with class-specific information.

def make_repr(self, special):
return '<%s instance at 0x%x: %s>' % (self.__class__.__name__,
id(self), special)
def __repr__(self):
return self.make_repr(repr(self.my_favorite_things))

This omits the module qualifier for the class name, but
arguably that's a bit of a nuisance anyway. If there's a
best, common practice way to do it, I wouldn't care to pose
as an expert in such things, so you have to decide for yourself.

Donn Cave, do**@u.washington.edu
Nov 3 '05 #8

This discussion thread is closed

Replies have been disabled for this discussion.