Author serhiy.storchaka
Recipients serhiy.storchaka
Date 2019-05-04.13:10:23
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1556975423.86.0.374987997006.issue36793@roundup.psfhosted.org>
In-reply-to
Content
object.__str__() calls the __repr__() method. Therefore by default you do not need to define the __str__() method if it is the same as __repr__(): just define the __repr__() method. But there are few builtin classes which define both __repr__() and __str__() methods which are equal. In most cases this is a legacy of Python 2 where they where different.

1. float and complex. In earlier Python 2 versions the repr of floating point number was longer (and more precise) that the str which was limited for readability. This was changed several times and in Python 3 the repr and the str are equal and contain as much digits as needed for the closest decimal approximation.

2. int. In Python 2 the repr of long integer was different from the str: it contained the "L" suffix.

3. bool. Since it is an int subclass with different repr, it needs to define __str__ to override int's __str__.

4. subprocess.Handle and sre_constants._NamedIntConstant. As bool they need to override int's __str__.

5. doctest.DocTestCase, doctest.DocFileCase. They need to override unittest.TestCase's __str__.

6. http.client.IncompleteRead, xmlrpc.client.Error. They need to override BaseException's __str__ (don't know why they want to do this).

7. asyncore.dispatcher, email.charset.Charset, logging.LogRecord, xmlrpc.client.MultiCall, xmlrpc.client.ServerProxy, decimal.Context (C implementation only), _pydecimal._WorkRep.  There is no need to define __str__.

In most of these cases the __str__ definition is redundant and can be removed. In cases 5 and 6 it is better to reset __str__ to object.__str__.

The only failing tests in the Python testsuite is the json module test. The json module calls int.__str__ explicitly. It can be fixed by replacing it with int.__repr__.

The user visible effect of these changes is that defining __repr__ in a subclass of these classes will affect the str() result (as for most of other classes). Although it is unlikely that you want to keep the str representation of the parent class when change the repr in the child class.
History
Date User Action Args
2019-05-04 13:10:24serhiy.storchakasetrecipients: + serhiy.storchaka
2019-05-04 13:10:23serhiy.storchakasetmessageid: <1556975423.86.0.374987997006.issue36793@roundup.psfhosted.org>
2019-05-04 13:10:23serhiy.storchakalinkissue36793 messages
2019-05-04 13:10:23serhiy.storchakacreate