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?
bytearraytobytesincurs a copy. This is because if the newbytespoints to the same backing array as thebytearray, then it wouldn't be truly immutable.bytearraywithout making a copy, you can use amemoryviewfor the purpose. The caveat is that changes to thebytearraydata will change the data in thememoryview, and that thebytearraycannot be resized (noappends,pops, resizing slice assignments, etc.) for as long as any exported buffers (of whichmemoryviewis the most common type created in Python level code) exist.buffer()to make a read-only buffer out of abytearraywithout actually performing a copy