5

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.

Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
Hatshepsut
  • 5,962
  • 8
  • 44
  • 80
  • My guess is that it shouldn't return unicode, since repr() is supposed to be used for the programmer (not the user), and some consoles don't support unicode. – paper man Jan 16 '18 at 01:35

2 Answers2

8

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.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • 7
    `str` is unicode in Python3 and bytes in Python2. I believe the OP is looking for those details – cowbert Jan 16 '18 at 01:38
  • @cowbert -- No, `str` is `str` in both. Python3 has no unicode type (just as python2 has no bytes type). Semantically, python3's `str` is the functional equivalent to python2.x's `unicode` if that's what you're trying to say... – mgilson Jan 16 '18 at 01:42
  • 4
    @mgilson the OP is clearly asking if repr returns an object with a bytes or unicode representation and is clearly wondering about the Py2 vs Py3 difference. In Py3, `str` is a unicode object. – cowbert Jan 16 '18 at 01:47
  • 5
    It could be worded better. The type is `str` in both, but they mean completely different things...! – wim Jan 16 '18 at 02:03
  • 1
    Also of interest: the accessors for both `__str__()` and `__repr__()` require the return type to be set to `str`. In Py3k I tried overriding both `__str__()` and `__repr__()` to return `b''` and all of `print()` (which calls `__str__()`), `str()`, and `repr()` (which calls `__repr__()` will yield a `TypeError: ... returned non-string (type bytes)`. – cowbert Jan 16 '18 at 04:47
1

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.)

rassar
  • 5,412
  • 3
  • 25
  • 41