从 bytearray 转换为 bytes 会产生一个副本吗?

Does converting from bytearray to bytes incur a copy?

从可变 bytearray 类型转换为非可变 bytes 类型会产生副本吗?是否有任何与之相关的成本,或者解释器是否只是将其视为不可变的字节序列,就像在 C++ 中将 char* 转换为 const char* const

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

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

这在 Python 3 和 Python 2.7 之间有区别吗,其中 bytes 是它自己的类型?Python 2.7 bytes 只是 str 的别名?

创建了一个新副本,bytesarray 和新的 bytes 对象之间不共享缓冲区,在 Python 2 或 3 中。

您无法共享它,因为 bytesarray 对象仍然可以在别处引用并改变值。

有关详细信息,请参阅 bytesobject.c source code, where the buffer protocol is used to create a straight up copy of the data (via PyBuffer_ToContiguous())。

马丁说得对。我只是想用 cpython 源代码来支持这个答案。

正在查看字节的来源 here, first bytes_new is called, which will call PyBytes_FromObject, which will call _PyBytes_FromBuffer, which creates a new bytes object and calls PyBuffer_ToContiguous (defined here)。这调用了buffer_to_contiguous,这是一个内存复制函数。该函数的注释如下:

Copy src to a contiguous representation. order is one of 'C', 'F' (Fortran) or 'A' (Any). Assumptions: src has PyBUF_FULL information, src->ndim >= 1, len(mem) == src->len.

因此,使用 bytearray 参数调用 bytes 将复制数据。