473,386 Members | 1,745 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Rich __repr__

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
7 3355
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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: Jim Newton | last post by:
hi all, does anyone know what print does if there is no __str__ method? i'm trying ot override the __repr__. If anyone can give me some advice it would be great to have. I have defined a...
3
by: Dan Sommers | last post by:
Hi, I have a class whose objects represent physical quantities including uncertainties and units, and I would like more control over the way they print. I have a __str__ method which outputs...
2
by: could ildg | last post by:
What's the difference between __repr__ and __str__? When will __repr__ be useful?
15
by: Jan Danielsson | last post by:
Sorry, but I Just Don't Get It. I did search the 'net, I did read the FAQ, but I'm too dumb to understand. As far as I can gather, __str__ is just a representation of the object. For instance: ...
8
by: Claudio Grondi | last post by:
It is maybe not a pure Python question, but I think it is the right newsgroup to ask for help, anyway. After connecting a drive to the system (via USB or IDE) I would like to be able to see...
1
by: Martin Drautzburg | last post by:
I am using repr() to pass arrays, dicts and combinations therof to javascript as it already returns a valid javascript expression (a string) right away. But for some reason it does not handle...
0
by: Roc Zhou | last post by:
Now I have to design a class that overload __getattr__, but after that, I found the __repr__ have been affected. This is a simple example model: #!/usr/bin/env python class test: def...
7
by: Roc Zhou | last post by:
Now I have to design a class that overload __getattr__, but after that, I found the __repr__ have been affected. This is a simple example model: #!/usr/bin/env python class test: def...
3
by: srinivasan srinivas | last post by:
Hi, I am getting an error while executing the following snippet. If i comment out method __repr__ , it works fine. class fs(frozenset):     def __new__(cls, *data):         data = sorted(data)...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.