[Tutor] Why difference between printing string & typing its object reference at the prompt?

Steven D'Aprano steve at pearwood.info
Thu Oct 4 13:45:42 CEST 2012

On 04/10/12 13:11, boB Stepp wrote:

> What happens if str() or repr() is not supported by a particular
> object? Is an exception thrown, an empty string returned or something
> else I am not imagining?

I don't think that is possible, at least not by accident or neglect.
In Python 3, everything inherits from object, which supports both str
and repr, so everything else should too:

py> class MyClass:
...     pass
py> obj = MyClass()
py> str(obj)
'<__main__.MyClass object at 0xb7c8c9ac>'
py> repr(obj)
'<__main__.MyClass object at 0xb7c8c9ac>'

Not terribly exciting, but at least it tells you what the object is,
and gives you enough information to distinguish it from other, similar,

I suppose you could write a class that deliberately raised an exception
when you called str() on it, in which case it would raise an exception
when you called str() on it... :) Likewise for repr().

py> class Stupid:
...     def __str__(self):
...             raise TypeError('cannot stringify this object')
py> obj = Stupid()
py> str(obj)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<stdin>", line 3, in __str__
TypeError: cannot stringify this object

> What larger phrase does "repr" stand for? My text mentions
> "representational form" later in the book, which sounds similar in
> concept to what you are discussing.

repr is short for "representation", as in "string representation".

> As I go along in my study of Python will it become clear to me when
> and how repr() and str() are being "...used, or implied in many
> places"?

Generally, print and the interactive interpreter are the only implicit
string conversions. At least the only ones I can think of right now...
no, wait, there's another one, error messages.

print() displays the str() of the object. The interactive interpreter
displays the repr() of the object. Error messages could do whatever
they like. Anything else, you have to explicitly convert to a string
using the form you want:

s = repr(x).lower()
t = str(y).replace('ss', 'ß')

or whatever.


More information about the Tutor mailing list