473,788 Members | 2,707 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 #1
15 2937
Jan Danielsson a écrit :
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.
.... yep, and this representation is built for human eyes. Don't
worry too much if it does not display every bit of information
contained in your object. Pretty printing rules ...
str(0.1) 0.1 str("it's a bad idea") "it's a bad idea"
However, I don't understand what __repr__ should be.
It is an *exact* (if possible) description of the object's content,
nicely packaged into a string.
repr(0.1) 0.1000000000000 0001 repr("it's a bad idea")

'"it\'s a bad idea"'

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).".


It means that the equality eval(repr(x)) == x should hold.

Cheers,

SB

Jul 19 '05 #2

Errata:
str(0.1) '0.1' str("it's a bad idea") "it's a bad idea"
repr(0.1) ' 0.1000000000000 0001' repr("it's a bad idea")

'"it\'s a bad idea"'
SB

Jul 19 '05 #3
Well, It means that eval(repr(x)) == x if at all possible.
Basically:
repr('abc') -> 'abc'
str('abc') -> abc

You'll notice that 'abc' is a valid python expression for the string,
while abc is not a valid string expression.

Andreas

On Wed, Jun 15, 2005 at 02:46:04PM +0200, Jan Danielsson wrote:
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?
--
http://mail.python.org/mailman/listinfo/python-list

Jul 19 '05 #4
Basically __repr__ should return a string representaion of the object,
and __str__ should return a user-friendly pretty string. So maybe:

class Person:
...
def __repr__(self):
return '<Person: %s, %d, %s>' % (self.name, self.age, self.sign)

def __str__(self):
return self.name

See this for a better explanation:

http://www.faqts.com/knowledge_base/...d/1331/fid/241
Jul 19 '05 #5
Jan Danielsson wrote:
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. [snip] However, I don't understand what __repr__ should be.


__repr__ shouldn't be anything, if you don't have an actual need for it.
Neither should __str__.

But if you have a need for something, and you're not sure which to use,
think of it this way. If you are trying to output a representation of
the object for use in debugging, such as in a debug log file, then use
__repr__ and make it look like whatever you want, but preferably
following the <Angle brackets convention> like all the builtin stuff.

If you have a need for some representation of the data to use in your
application for non-debugging purposes, such as perhaps to display data
to a user, or to write data to an output file, then __str__ is a good
candidate, and you can make it look like whatever you need.

Just don't waste your time defining either a __repr__ or a __str__ just
because those methods exist. That won't do anyone any good.

-Peter
Jul 19 '05 #6
In article <42********@gri seus.its.uu.se> ,
Jan Danielsson <ja************ @gmail.com> wrote:
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.
No, it is not. It is a conversion to string. The result has
no trace of the original object, per se -- in principle, many
different kinds of object could yield the same result. Suppose
str(x) -> "42". Is x an int? a string? an XMLParseResult?
AnswerToLifeThe UniverseAndEver ything? You don't want to know,
that's why you use str().

The "friendly" idea is vacuous if you look hard enough at it,
and won't really help.
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?


It's kind of a bad idea that the Python world isn't ready to
let go of yet.

repr() is really the representation of the object. If you
look at the result of repr(x), you should indeed see some
clue to the original object. I guess this is what gives
people the idea that str() is friendly, because as a rule
users are not interested in the original object -- but
there are exceptions, for example you may find the quotes
useful around a string, depending on the situation. The
object information also leads to the marshalling idea, but
of course this isn't (and can't be) implemented for many
objects so we can't expect this to work reliably with
random objects. The price we pay for the notion is mostly
in the "fix" for float repr, which now displays the float
in all its imprecise glory and routinely confounds people
who don't understand what that's about.

Donn Cave, do**@u.washingt on.edu
Jul 19 '05 #7
On Wednesday 15 June 2005 08:06 am, Sébastien Boisgérault wrote:
Jan Danielsson a écrit :
However, I don't understand what __repr__ should be.

It is an *exact* (if possible) description of the object's content,
nicely packaged into a string.


However, this is often not the case. Frequently __repr__ will
return something like this:
import re
r = re.compile('\w+ \d*')
r <_sre.SRE_Patte rn object at 0x401a89b0> str(r) '<_sre.SRE_Patt ern object at 0x401a89b0>' repr(r)

'<_sre.SRE_Patt ern object at 0x401a89b0>'

So don't obsess over it. For many objects it isn't worth
the trouble, and for others, str() and repr() are sensibly the
same thing, but for some, the distinction is useful. That's
all.

--
Terry Hancock ( hancock at anansispacework s.com )
Anansi Spaceworks http://www.anansispaceworks.com

Jul 19 '05 #8
Jan Danielsson wrote:
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.


Say we define a string "s" as follows:
s = 'hello'
If we print "s", we see its string form (__str__):
print s hello

However, if we just examine "s", we see its representation (__repr__):
s 'hello'

This can be verified by calling str() and repr() on the string:
str(s) 'hello' repr(s) "'hello'"

So, the result of repr() includes quotes, whereas the result of str()
does not. This has useful properties when the object is part of a more
complex structure. For instance, these two expressions print out the same:
[s, s] ['hello', 'hello'] print [s, s] ['hello', 'hello']

That's because, in either case, the repr() form is used. If Python only
had str(), we would probably expect str(s) = s, so we'd instead see
something like this imaginary snippet:
[s, s] [hello, hello] repr([s, s]) '[hello, hello]'

So, the convention in Python is that repr() returns a string that, when
evaluated, returns the original object. This is not always easy or
possible to do, but if you can do it, your objects will print nicely
when nested within Python's built-in data structures. Python's actual
behavior is this:
repr([s, s]) "['hello', 'hello']"

And therefore:
eval(repr([s, s]))

['hello', 'hello']

Also worth noting is that if you define __repr__, the default behavior
of __str__ is to delegate to that definition, so if you only want to
define one, it's often more convenient to just define __repr__.

Dave
Jul 19 '05 #9

"Jan Danielsson" <ja************ @gmail.com> wrote in message
news:42******** @griseus.its.uu .se...
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?


str() should be something that's meaningful to a human being when
it's printed or otherwise rendered. repr() should be something that
can round trip: that is, if you feed it into eval() it should reproduce
the object.

You can't always achieve either one, especially with very
complex objects, but that's the goal.

John Roth

Jul 19 '05 #10

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
3007
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
3369
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
1481
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
2336
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
5053
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
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
10177
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
10113
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
8995
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
7519
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
5402
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...
0
5538
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2896
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.