New submission from Serhiy Storchaka <storchaka+cpyt...@gmail.com>:

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.

----------
components: Interpreter Core
messages: 341382
nosy: serhiy.storchaka
priority: normal
severity: normal
status: open
title: Do not set tp_str
versions: Python 3.8

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue36793>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to