-
-
Notifications
You must be signed in to change notification settings - Fork 29.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Do not define unneeded __str__ equal to __repr__ #80974
Comments
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.
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. |
I like this. Always annoying to explicitly override both __repr__ and __str__ on subclasses of stuff like int when they should be the same. Patch looks good to me; I was originally wondering why some classes were replacing: __str__ = __repr__ with: __str__ = object.__str__ but checking their inheritance chains, it's clear *some* overload is needed for consistency, and using object.__str__ means reverting to the default case where subclasses only need to overload __repr__, rather than forcing all subclasses to overload both. |
Serhiy: Did you plan to do any further work, or can this issue be closed? |
by manually defining the function where needed Change in python 3.8, causing "TypeError" not to be thrown: https://docs.python.org/3/whatsnew/3.8.html "Removed __str__ implementations from builtin types bool, int, float, complex" See also python/cpython#80974 python/cpython#80974
by manually defining the function where needed Change in python 3.8, causing "TypeError" not to be thrown: https://docs.python.org/3/whatsnew/3.8.html "Removed __str__ implementations from builtin types bool, int, float, complex" See also python/cpython#80974 python/cpython#80974
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: