Title: bytes does not implement __bytes__()
Type: behavior Stage:
Components: Interpreter Core Versions: Python 3.8, Python 3.7, Python 3.6
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: FHTMitchell, serhiy.storchaka, terry.reedy
Priority: normal Keywords:

Created on 2018-03-12 14:28 by FHTMitchell, last changed 2018-03-16 22:12 by terry.reedy.

Messages (3)
msg313653 - (view) Author: FHTMitchell (FHTMitchell) Date: 2018-03-12 14:28
Every object which has a corresponding dunder protocol also implements said protocol with one exception:

>>> 'hello'.__str__()

>>> (3.14).__float__()

>>> (101).__int__()

>>> True.__bool__()

>>> iter(range(10)).__iter__()
<range_iterator at 0xf6b08b0>

>>> b'hello'.__bytes__()
AttributeError                            Traceback (most recent call last)
----> 1 b'hello'.__bytes__()

AttributeError: 'bytes' object has no attribute '__bytes__'

This was brought up on SO as being inconsistent:
msg313666 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2018-03-12 16:27
This isn't one exception. For example complex doesn't have the __complex__ method.

__str__, __float__, __int__ and __bool__ are implemented in str, float, int and bool because there are corresponding special slots in a type object. But __bytes__ and __complex__ were added later and they have no slots. Calling them for bytes and complex will slowdown creating new object.

The user code rarely needs to call these methods directly. Just call bytes(), complex(), str(), float(), etc.
msg313977 - (view) Author: Terry J. Reedy (terry.reedy) * (Python committer) Date: 2018-03-16 22:12
It is against Guido's general policy to add things not needed purely for consistency.  Unless there is a compelling use case, I think this should be closed.

FHTM: I don't think Serhiy posts on SO, so you might consider adding his answer to yours, or make it a separate answer.
Date User Action Args
2018-03-16 22:12:18terry.reedysetnosy: + terry.reedy
messages: + msg313977
2018-03-12 16:27:52serhiy.storchakasetnosy: + serhiy.storchaka
messages: + msg313666
2018-03-12 14:28:02FHTMitchellcreate