Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does converting from bytearray to bytes incur a copy?

Does converting from the mutable bytearray type to the non-mutable bytes type incur a copy? Is there any cost associated with it, or does the interpreter just treat it as an immutable byte sequence, like casting a char* to a const char* const in C++?

ba = bytearray()
ba.extend("some big long string".encode('utf-8'))

# Is this conversion free or expensive?
write_bytes(bytes(ba))

Does this differ between Python 3 where bytes is its own type and Python 2.7 where bytes is just an alias for str?

like image 716
JDS Avatar asked Mar 08 '16 23:03

JDS


1 Answers

A new copy is created, the buffer is not shared between the bytesarray and the new bytes object, in either Python 2 or 3.

You couldn't share it, as the bytesarray object could still be referenced elsewhere and mutate the value.

For the details, see the bytesobject.c source code, where the buffer protocol is used to create a straight up copy of the data (via PyBuffer_ToContiguous()).

like image 115
Martijn Pieters Avatar answered Oct 20 '22 07:10

Martijn Pieters