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

Terry Reedy tjreedy at udel.edu
Wed Oct 12 15:44:19 EDT 2016


On 10/12/2016 5:42 AM, INADA Naoki wrote:
> On Wed, Oct 12, 2016 at 2:32 PM, Serhiy Storchaka <storchaka at gmail.com> wrote:
>> On 12.10.16 07:08, INADA Naoki wrote:
>>>
>>> Sample code:
>>>
>>>     def read_line(buf: bytearray) -> bytes:
>>>         try:
>>>             n = buf.index(b'\r\n')
>>>         except ValueError:
>>>             return b''
>>>
>>>         line = bytes(buf)[:n]  # bytearray -> bytes -> bytes
>>
>>
>> Wouldn't be more correct to write this as bytes(buf[:n])?
>
> Yes, you're right!
> I shouldn't copy whole data only for cast from bytearray to byte.

Also, why do the conversion from bytearray to bytes?  It is definitely 
not always needed.

 >>> ba = bytearray(b'abc')
 >>> b = b'def'
 >>> ba + b
bytearray(b'abcdef')
 >>> b'%s %s' % (ba, b)
b'abc def'
 >>> b + ba
b'defabc'
 >>> ba.extend(b)
 >>> ba
bytearray(b'abcdef')

Even if it is sometimes needed, why do it always?  The essence of 
read_line is to slice out a line, delete it from the buffer, and return 
the line.  Let the caller explicitly convert when needed.

-- 
Terry Jan Reedy



More information about the Python-Dev mailing list