14
What is the difference between the methods __str__
and __repr__
?
They both do the same thing?
14
What is the difference between the methods __str__
and __repr__
?
They both do the same thing?
16
The __str__
serves to display the object to end user, used by the command print and by function str
The __repr__
serves to display the object to the programmer, used by console of Python and the function repr
.
Example:
>>> import datetime
>>> today = datetime.datetime.now()
>>> str(today)
'2012-03-14 09:21:58.130922'
>>> repr(today)
'datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)'
See more here about repr
and here about str
in the documentation.
Just complementing, in Python, there is still a third method: __unicode__
, that works like the __str__
but generates a representation
object in the form of an instance of Unicode (instead of a string of
bytes, which is what the other two do). See here the comparison.
Interestingly, I didn’t even know there was such a function repr
:p
by the way, inverse of Repr is Eval : eval(repr(today)) == today
Ah, so the repr
is equivalent to var_export
of PHP.
@Wallacemaxters are two very close functions with the same purpose. In PHP there is still the var_dump
which approaches a little, but the returned representation is a valid PHP code.
It is worth adding that if you just set __repr__()
and did not define __str__()
, then the first is used as fallback of the second. And __repr__()
has no fallback.
7
Summary
__repr__
__str__
The responses of users Alex Martelli and Md. Abu Nafee Ibna Zahid are very good.
Here is my translation and remix of answers in English:
What’s the difference between
__str__
and__repr__
?
This may be a little strange since standard Python implementations tend to be helpful. But in this case have a standard implementation for __repr__
might be something like:
return '%s(%r)'.format(self.__class__, self.__dict__)
But it can also be dangerous (for example, it is easy to enter an infinite recursion if objects reference each other). In this case python wallow. Note that it is a pattern when one of them is implemented: If __repr__
was set and __str__
was not the object will behave as __str__=__repr__
.
In simple terms, this means: virtually every object you implement should contain the __repr__
which will be used to "comprehend" the object. Implement __str__
is optional, do this if you need the functionality of "Pretty print" for example used by a report generator.
__repr__
is to be unambiguousMd. Abu is a programmer who is not a fan of debug-ers and claims that he barely knows how to use one and has never used one seriously. He states that the debug-ers have a basic flaw in their nature and that believes with a religious faith in logging
. It states with conviction that logging
is the life force of any decent server system of the type fire-and-Forget (fire-and-forget). And we agree that with python it’s easy to make log: perhaps with some projects of Wrappers specific, all you need is:
log(INFO, "Eu sou uma função esquisita e A é", A, "e B é", b, "mas tenho null em C — usando default", default_C)
But you have to do the last step - make sure that every object you implement has one useful comparison, then the code as quoted will work properly. That’s why the "eval
" appears: if you have enough information then eval(repr(c)) == c
, that means you know everything there is to know about c
. If this is easy enough or at least in a confusing way, do it. If not, make sure you have enough information about c
anyway. Md. Abu says it usually uses a format similar to eval
: " MinhaClasse(isso=%r, aquilo=%r)" % (self.isso, self.aquilo)
. That doesn’t mean you can actually build MinhaClasse
, or that these are the correct constructor arguments - but it’s a useful way to express "that’s all you need to know about this instance".
Note: Md. Abu used above %r
and not %s
. You’ll always want to use repr()
(or %r
the formatting character equivalently) within the implementation __repr__
or you will be running away from the goal of repr
. So you will be able to differentiate MinhaClasse(3)
of MinhaClasse("3")
.
__str__
is to be legibleSpecifically, not if the intention is to be unambiguous - note that str(3) == str("3")
. Similarly, if you implement an abstraction for IP, have the str
with the value 192.168.1.1 is ok. Already when implementing a date/time abstraction, the str
can be "2010/4/12 15:35:22", etc. The goal is to represent in a way that a user, not a programmer would like to read it. Cutting useless digits, pretending to be some other class - as long as it helps with readability, is an improvement.
__str__
utilize __repr__
Note: This part is very complicated to translate, so comments and edits are welcome
Sounded weird didn’t it? A little, how readable is that
[moshe is, 3, hello
world, this is a list, oh I don't know, containing just 4 elements]
Readable? Not too much. Specifically, strings in a list are very easy to match their string representation. In the face of ambiguity, remember, Python resists the temptation to guess. If you want the above behavior when printing a list.
l = ['moshe is', '3', 'hello \nworld', 'this is a list', 'oh I don\'t know', 'containing just 4 elements']
print("[" + ", ".join(l) + "]")
(you can probably also figure out what to do about Dictionaries.
Implement __repr__
for any class you implement. Implement __str__
if you find it useful to have a string version that gives more readability in favor of having more ambiguity.
Browser other questions tagged python characteristic-language
You are not signed in. Login or sign up in order to post.
Here on Soen answers: http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python
– viana