Does conversion from byte to byte convert copy?

Is conversion from a mutable bytearray type to a non-mutable bytes type of bytearray ? Is there any value associated with it, or does the interpreter simply treat it as an immutable sequence of bytes, for example, casting char* to 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)) 

Differences between Python 3, where bytes is its own type and Python 2.7, where bytes is just an alias for str ?

+5
source share
2 answers

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

You could not share it, since the bytesarray object bytesarray still be referenced elsewhere and change the value.

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

+11
source

Margin is right. I just wanted to support this answer with cpython source.

Looking at the byte source here , the first bytes_new , which is called PyBytes_FromObject , which is called _PyBytes_FromBuffer , which creates a new byte object and calls PyBuffer_ToContiguous (defined here ). This calls buffer_to_contiguous , which is a memory copy function. Comment for function:

Copy src to the adjacent view. the order is one of "C", "F" (Fortran) or "A" (any). Assumptions: src has PyBUF_FULL information, src-> ndim> = 1, len (mem) == src-> len.

So calling bytes with bytearray will copy the data.

+7
source

Source: https://habr.com/ru/post/1244695/


All Articles