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

eryksun eryksun at gmail.com
Thu Oct 4 19:27:53 CEST 2012

On Wed, Oct 3, 2012 at 11:11 PM, boB Stepp <robertvstepp at gmail.com> 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?

The __str__ method inherited from "object" calls __repr__.

For a class, __repr__ is inherited from type.__repr__, which returns
"<class 'module_name.class_name'>".

For an instance, __repr__ is inherited from object.__repr__, which returns
"<module_name.class_name object at address>".

If you override __str__ or __repr__, you must return a string. Else
the interpreter will raise a TypeError.

Basic example:

    >>> class Test:...

repr of the class:

    >>> repr(Test)
    "<class '__main__.Test'>"

repr of an instance:

    >>> repr(Test())
    '<__main__.Test object at 0x958670c>'

> 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"?

str is Python's string type, while repr is a built-in function that
returns a string suitable for debugging.

You can also call str without an argument to get an empty string, i.e.
str() == ''. This is similar to other built-in types: int() == 0,
float() == 0.0, complex() == 0j, tuple() = (), list() = [], and dict =
{}. The returned value is either 0 or empty -- and boolean False in
all cases.

str also takes the optional arguments "encoding" and "errors" to
decode an encoded string:

    >>> str(b'spam', encoding='ascii')

bytes and bytearray objects have a decode() method that offers the
same functionality:

    >>> b'spam'.decode('ascii')

But other objects that support the buffer interface might not. For
example, take the following array.array with the ASCII encoded bytes
of "spam":

    >>> arr = array.array('B', b'spam')

Here's the repr:

    >>> arr
    array('B', [115, 112, 97, 109])

Without an argument str just returns the repr of the array:

    >>> print(arr)
    array('B', [115, 112, 97, 109])

(The print function calls str.)

But we can tell str to treat the array as an ASCII encoded buffer:

    >>> print(str(arr, 'ascii'))

More information about the Tutor mailing list