Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 876
Hatshepsut Avatar asked Jan 16 '18 01:01

Hatshepsut


People also ask

What does__ repr__ do?

According to the official documentation, __repr__ is used to compute the “official” string representation of an object and is typically used for debugging.

When to use__ repr__?

The __repr__() special method is used within classes to return the string representation of an object, which is returned when instances from that class are supplied as arguments to print() or repr().

When__ repr__ is called?

Earlier we mentioned that if we don't implement __str__ function then the __repr__ function is called. Just comment the __str__ function implementation from the Person class and print(p) will print {name:Pankaj, age:34} .

What is the difference between__ str__ and__ repr__?

str() is used for creating output for end user while repr() is mainly used for debugging and development. repr's goal is to be unambiguous and str's is to be readable.


1 Answers

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.

like image 79
mgilson Avatar answered Oct 02 '22 11:10

mgilson