[Python-Dev] Adding bytes.frombuffer() constructor to PEP 467

Serhiy Storchaka storchaka at gmail.com
Thu Jan 5 17:54:57 EST 2017


On 05.01.17 22:37, Alexander Belopolsky wrote:
> I propose the following:
>
> 1. For 3.6, restore and document 3.5 behavior.  Recommend that 3rd party
> types that are both integer-like and buffer-like implement their own
> __bytes__ method to resolve the bytes(x) ambiguity.

The __bytes__ method is used only by the bytes constructor, not by the 
bytearray constructor.

> 2. For 3.7, I would like to see a drastically simplified bytes(x):
> 2.1.  Accept only objects with a __bytes__ method or a sequence of ints
> in range(256).
> 2.2.  Expand __bytes__ definition to accept optional encoding and errors
> parameters.  Implement str.__bytes__(self, [encoding[, errors]]).

I think it is better to use the encode() method if you want to encode 
from non-strings.

> 2.3.  Implement new specialized bytes.fromsize and bytes.frombuffer
> constructors as per PEP 467 and Inada Naoki proposals.

bytes.fromsize(n) is just b'\0'*n. I don't think this method is needed.

bytes.frombuffer(x) is bytes(memoryview(x)) or memoryview(x).tobytes().

> 2.4. Implement memoryview.__bytes__ method so that bytes(memoryview(x))
> works ad before.
> 2.5.  Implement a fast bytearray.__bytes__ method.

This wouldn't help for the bytearray constructor. And wouldn't allow to 
avoid double copying in the constructor of bytes subclass.

> 3. Consider promoting __bytes__ to a tp_bytes type slot.

The buffer protocol is more general than the __bytes__ method. It allows 
to avoid redundant memory copying in constructors of many types (bytes, 
bytearray, array.array, etc), not just bytes.




More information about the Python-Dev mailing list