473,800 Members | 2,380 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

FAQ: __str__ vs __repr__

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 ServerConnectio n:
def __str__(self):
buf = "Server: " + self.name + "\n"
buf += "Sent bytes: " + str(self.sentBy tes) + "\n"
buf += "Recv bytes: " + str(self.recvBy tes) + "\n"
return buf

However, I don't understand what __repr__ should be. There's a phrase
in the documentation which makes it highly confusing for a beginner like
me: "If at all possible, this should look like a valid Python expression
that could be used to recreate an object with the same value (given an
appropriate environment).". What does that mean? Does it mean that I
should return:

def __str__(self):
buf = "self.name= " + self.name + "\n"
buf += "self.sentBytes =" + str(self.sentBy tes) + "\n"
buf += "self.recvBytes =" + str(self.recvBy tes) + "\n"
return buf

..or is there some other "valid Python expression" format which I
have yet to encounter?
Jul 19 '05
15 2940
Quoth "John Roth" <ne********@jhr othjr.com>:
....
| str() should be something that's meaningful to a human being when
| it's printed or otherwise rendered.

I can't believe how many people cite this explanation - meaningful,
friendly, pretty to a human being. What on earth does this mean,
that couldn't be said more unambiguously?

According to my impression of common applications for Python programs,
rarely would anyone be looking at the output for esthetic gratification.
I mean, imagine your users casting an appraising eye over the contours
of a phrase emitted by the program, and praising the rhythmic effect of
the punctuation it chose to use, or negative space created by tabs. heh.

Whether for human eyes or any destination, properly formed output will
carry the information that is required for the application, in a complete
and unambiguous way and in the format that is most readily processed,
and it will omit extraneous information. Are we saying anything other
than this?

Donn Cave, do**@drizzle.co m
Jul 19 '05 #11

"Donn Cave" <do**@drizzle.c om> wrote in message
news:1118898421 .887013@yasure. ..
Quoth "John Roth" <ne********@jhr othjr.com>:
...
| str() should be something that's meaningful to a human being when
| it's printed or otherwise rendered.

I can't believe how many people cite this explanation - meaningful,
friendly, pretty to a human being. What on earth does this mean,
that couldn't be said more unambiguously?

According to my impression of common applications for Python programs,
rarely would anyone be looking at the output for esthetic gratification.
I mean, imagine your users casting an appraising eye over the contours
of a phrase emitted by the program, and praising the rhythmic effect of
the punctuation it chose to use, or negative space created by tabs. heh.

Whether for human eyes or any destination, properly formed output will
carry the information that is required for the application, in a complete
and unambiguous way and in the format that is most readily processed,
and it will omit extraneous information. Are we saying anything other
than this?
I thought that's what I said. I fail to see how you derive any other
meaning from it. Possibly less verbiage and a concerete example
of how "meaningful " equates to "esthetics that obfustificate understanding"
and does not equate to "immediatel y useable, without having to wade
through a lot of irrelvant mental transformations " would help my
understanding.

John Roth
Donn Cave, do**@drizzle.co m


Jul 19 '05 #12
In article <11************ *@news.supernew s.com>,
"John Roth" <ne********@jhr othjr.com> wrote:
"Donn Cave" <do**@drizzle.c om> wrote in message
news:1118898421 .887013@yasure. ..
Quoth "John Roth" <ne********@jhr othjr.com>:
...
| str() should be something that's meaningful to a human being when
| it's printed or otherwise rendered.

I can't believe how many people cite this explanation - meaningful,
friendly, pretty to a human being. What on earth does this mean,
that couldn't be said more unambiguously?

According to my impression of common applications for Python programs,
rarely would anyone be looking at the output for esthetic gratification.
I mean, imagine your users casting an appraising eye over the contours
of a phrase emitted by the program, and praising the rhythmic effect of
the punctuation it chose to use, or negative space created by tabs. heh.

Whether for human eyes or any destination, properly formed output will
carry the information that is required for the application, in a complete
and unambiguous way and in the format that is most readily processed,
and it will omit extraneous information. Are we saying anything other
than this?


I thought that's what I said. I fail to see how you derive any other
meaning from it. Possibly less verbiage and a concerete example
of how "meaningful " equates to "esthetics that obfustificate understanding"
and does not equate to "immediatel y useable, without having to wade
through a lot of irrelvant mental transformations " would help my
understanding.


Not sure if that's a question. Maybe I can state this more clearly.

Observation: Most who responded to this question offered an
explanation of __str__ like "friendly to a human being",
using one or more of meaningful, friendly or pretty. The
online manual uses "informal".

1. These words are woefully ambiguous, to be applied in computer
programming. While there may be some kind of absolute basis
for esthetic appreciation, that clearly doesn't apply here,
and terms like this have to be strictly relative to context
created by the application.
Summary: By itself, friendly to a human being is a vacuous
notion and doesn't help anyone.

2. If we attempt to support the explanation with a more rigorous
examination of the principles and how they'd apply to a string
conversion, it's hard to make this come out favoring str over
repr. In the end, they should both be meaningful and friendly,
by any uncontorted definition of those terms.
Summary: To the extent that they have any meaning, they are
probably applied incorrectly as an explanation of __str__.

So, among other conclusions, the documentation should be changed
to offer a more sensible explanation of __str__.

Donn Cave, do**@u.washingt on.edu
Jul 19 '05 #13
On 6/15/05, Peter Hansen <pe***@engcorp. com> wrote:
__repr__ shouldn't be anything, if you don't have an actual need for it.
Neither should __str__.


Oh, I don't know. __str__ is so frequently useful in debugging and
logging that I always try and do something useful with it.

--
Cheers,
Simon B,
si***@brunningo nline.net,
http://www.brunningonline.net/simon/blog/
Jul 19 '05 #14
Simon Brunning wrote:
On 6/15/05, Peter Hansen <pe***@engcorp. com> wrote:
__repr__ shouldn't be anything, if you don't have an actual need for it.
Neither should __str__.


Oh, I don't know. __str__ is so frequently useful in debugging and
logging that I always try and do something useful with it.


Interesting: for the same purpose, I would define __repr__.

But I still define it only when I actually care about the details, since
otherwise the default __repr__ is always there. Spending time figuring
out a potentially more useful __str__/__repr__ (how nice that we've
confused the issue of which to use, again! ;-) ) is not my idea of a
good use of time, what with YAGNI and all from XP...

-Peter
Jul 19 '05 #15
__repr__ shouldn't be anything, if you don't have an actual need for
it. Neither should __str__.


Simon> Oh, I don't know. __str__ is so frequently useful in debugging
Simon> and logging that I always try and do something useful with it.

And sometimes __repr__ inherited from a base class doesn't tell you much.
If you inherit from gobject (the basic object in PyGtk), the repr is
something like

<Future object (__main__+Base) at 0x851384c>

That is, it identifies the class name, its inheritance hierarchy (Future ->
Base -> __main__ in this case) and its memory address. That's perhaps
useful by itself in some contexts, and I can understand that the PyGtk folks
couldn't really stuff more specific info in there, but it does nothing to
distinguish one instance's state from that of another.

Skip
Jul 19 '05 #16

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
1827
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
3008
by: could ildg | last post by:
What's the difference between __repr__ and __str__? When will __repr__ be useful?
7
1913
by: Jeffrey E. Forcier | last post by:
I am attempting to write a class whose string representation changes in response to external stimuli. While that effect is obviously possible via other means, I attempted this method first and was surprised when it didn't work, so I now want to know why :) Given the following class definition: class MyClass(object): def Edit(self):
7
3370
by: Ben Finney | last post by:
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
1
1482
by: Edward C. Jones | last post by:
#! /usr/bin/env python class A(list): def __init__(self, alist, n): list.__init__(self, alist) self.n = n def __str__(self): return 'AS(%s, %i)' % (list.__str__(self), self.n)
7
2338
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:
5
5055
by: Konstantinos Pachopoulos | last post by:
Hi, i have the following class: =========================================== class CmterIDCmts: def __init__(self,commiterID,commits): self.commiterID_=long(commiterID) self.commits_=long(commits) def __str__(self):
0
9690
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
9551
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
10505
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10033
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
9085
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...
0
6811
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5471
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4149
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
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.