473,788 Members | 2,892 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3368
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.H uman_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__(se lf)
)
return repr_str

def __init__(self, name):
str.__init__(na me)
# [... 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**********@r ose.polar.local >, Ben Finney wrote:
class Human_Sex(str):
def __repr__(self):
repr_str = "%s(name=%s )" % (
self.__class__. __name__,
str.__repr__(se lf)
)
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**********@r ose.polar.local >, Ben Finney wrote:
class Human_Sex(str):
def __repr__(self):
repr_str = "%s(name=%s )" % (
self.__class__. __name__,
str.__repr__(se lf)
)
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.co m> 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**********@r ose.polar.local >,
Ben Finney <bi************ ****@benfinney. id.au> wrote:
Erik Max Francis <ma*@alcyone.co m> 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_fa vorite_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.washingt on.edu
Nov 3 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
5954
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 lisp-like linked list class as a subclass of list. The __iter__ seems to work as i'd like, by traversing the links, and the __repr__ seems to work properly for somethings but not others. The basic idea is that a list such as is converted to ]],...
3
1826
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 the quantity and its uncertainty, properly rounded (i.e. the uncertainty to one digit and the quantity to the same precision as the uncertainty), followed by the units (mostly) as they accumulated during whatever calculations led to the quantity's
2
3006
by: could ildg | last post by:
What's the difference between __repr__ and __str__? When will __repr__ be useful?
15
2937
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: class ServerConnection: def __str__(self): buf = "Server: " + self.name + "\n" buf += "Sent bytes: " + str(self.sentBytes) + "\n"
8
2134
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 within seconds if there were changes in the file system of that drive since last check (250 GB drive with about four million files on it). How to accomplish this? (best if providing
1
2450
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 Umlaute correctly and those characters finally appear as two strange characters on the browser. I am using UTF-8 and assembling the string expression manually works okay and the umlaute appear correctly in the browser (so I could probably write my own...
0
913
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 __init__(self): self.x = 1 def __getattr__(self, attr_name):
7
2335
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 __init__(self): self.x = 1 def __getattr__(self, attr_name): try:
3
1948
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)         self = frozenset.__new__(cls, data)         self.__data = data         return self
0
9656
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10175
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10112
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9969
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7518
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4070
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.