Hatshepsut
Hatshepsut

Reputation: 6662

Is __repr__ supposed to return bytes or unicode?

In Python 3 and Python 2, is __repr__ supposed to return bytes or unicode? A reference and quote would be ideal.

Here's some information about 2-3 compatibility, but I don't see the answer.

Upvotes: 5

Views: 1774

Answers (2)

mgilson
mgilson

Reputation: 310097

The type is str (for both python2.x and python3.x):

>>> type(repr(object()))
<class 'str'>

This has to be the case because __str__ defaults to calling __repr__ if the former is not present, but __str__ has to return a str.

For those not aware, in python3.x, str is the type that represents unicode. In python2.x, str is the type that represents bytes.

Upvotes: 8

rassar
rassar

Reputation: 5670

It's str in both languages:

Python 3.6.4 (default, Dec 21 2017, 18:54:30) 

>>> type(repr(()))
<class 'str'>

Python 2.7.14 (default, Nov  7 2017, 17:59:11) 
>>> type(repr(()))
<type 'str'>

(There's a tuple in there.)

Upvotes: 1

Related Questions