Rich __repr__

B

Ben Finney

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?
 
B

Ben Finney

Ben Finney said:
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:

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?
 
E

Erik Max Francis

Ben said:
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.
 
M

Marc 'BlackJack' Rintsch

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
 
B

Ben Finney

Marc 'BlackJack' Rintsch said:
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.
 
B

Ben Finney

Erik Max Francis said:
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?
 
E

Erik Max Francis

Ben said:
> 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.
 
D

Donn Cave

Ben Finney said:
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, (e-mail address removed)
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top