tags:

views:

109

answers:

3

I really don't understand where are __str__ and __repr__ used in Python. I mean, I get that __str__ returns the string representation of an object. But why would I need that? In what use case scenario? Also, I read about the usage of __repr__

But what I don't understand is, where would I use them?

+3  A: 

__repr__

Called by the repr() built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object. 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).

__str__

Called by the str() built-in function and by the print statement to compute the "informal" string representation of an object.

Use __str__ if you have a class, and you'll want an informative/informal output, whenever you use this object as part of string. E.g. you can define __str__ methods for Django models, which then gets rendered in the Django administration interface. Instead of something like <Model object> you'll get like first and last name of a person, the name and date of an event, etc.


__repr__ and __str__ are similar, in fact sometimes equal (Example from BaseSet class in sets.py from the standard library):

def __repr__(self):
    """Return string representation of a set.

    This looks like 'Set([<list of elements>])'.
    """
    return self._repr()

# __str__ is the same as __repr__
__str__ = __repr__
The MYYN
Thanks! This is exactly what I was looking for!
Daniel
+2  A: 

Grasshopper, when in doubt go to the mountain and read the Ancient Texts. In them you will find that __repr__() should:

If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value.

Peter Rowell
-1 as this doesn't even attempt to answer the actual question, which is what the use cases are.
Scott Griffiths
@Scott: You are correct. But then again the *actual question* showed absolutely no attempt to go to the primary docs in the first place. It's one thing to ask a question that shows you've made an attempt to answer it for yourself but are still a little confused about some aspect of it, and another thing altogether to post a question like this. Just typing in his subject line as a new question shows that 5 of the top 6 suggested SO threads would have answered his question, but he couldn't be bothered. I did not quite give him a lmgtfy answer, but I was sorely tempted.
Peter Rowell
Actually he did say that he'd read about `__repr__`, the official docs don't really answer the question as to why you'd use it, and just because a question is answered elsewhere isn't a good reason for it not also to be answered on SO (as often as not Googling will bring you back here!) If you don't think that the question is worth answering then you could just not answer it, though in this case I do agree that it's covered very well already on SO and so linking to duplicates would be an appropriate response.
Scott Griffiths
Peter Rowell
Well the docs still don't say *how* to use it for debugging, but I really didn't intend to get into an argument over this. We at least agree that your answer didn't address the question, so my -1 still feels justified to me. If a question is poorly written/a duplicate/trivial then you can help to improve the question, link to duplicates, or simply down-vote the question. I think my main objection here is that answers should try to answer the question - there are other mechanisms for criticising the question. I'll shut up now as I think we both have better things to do here.
Scott Griffiths
+3  A: 

The one place where you use them both a lot is in an interactive session. If you print an object then its __str__ method will get called, whereas if you just use an object by itself then its __repr__ is shown:

>>> from decimal import Decimal
>>> a = Decimal(1.25)
>>> print(a)
1.25                  <---- this is from __str__
>>> a
Decimal('1.25')       <---- this is from __repr__

The __str__ is intended to be as human-readable as possible, whereas the __repr__ should aim to be something that could be used to recreate the object, although it often won't be exactly how it was created, as in this case.

It's also not unusual for both __str__ and __repr__ to return the same value (certainly for built-in types).

Scott Griffiths