What is a bytes-like object
Question:
In Python 3.6, the base64.b64encode()
function requires "a bytes-like object, not str
".
What is an example of a bytes-like object as opposed to a normal string?
Answers:
Anything that logically stores a sequence of bytes qualifies. That includes the actual bytes
type, bytearray
, mmap.mmap
, array.array('B')
, etc. str
in Python 3 is a text type; the characters aren’t stored in a specified encoding, so you can’t use them as raw binary data directly; they must be encode
-ed explicitly with a specific encoding.
For the technical definition, see the Python 3 glossary:
An object that supports the Buffer Protocol and can export a C-contiguous buffer. This includes all bytes
, bytearray
, and array.array
objects, as well as many common memoryview
objects. Bytes-like objects can be used for various operations that work with binary data; these include compression, saving to a binary file, and sending over a socket.
Some operations need the binary data to be mutable. The documentation often refers to these as “read-write bytes-like objects”. Example mutable buffer objects include bytearray
and a memoryview
of a bytearray
. Other operations require the binary data to be stored in immutable objects (“read-only bytes-like objects”); examples of these include bytes
and a memoryview
of a bytes
object.
In Python 3.6, the base64.b64encode()
function requires "a bytes-like object, not str
".
What is an example of a bytes-like object as opposed to a normal string?
Anything that logically stores a sequence of bytes qualifies. That includes the actual bytes
type, bytearray
, mmap.mmap
, array.array('B')
, etc. str
in Python 3 is a text type; the characters aren’t stored in a specified encoding, so you can’t use them as raw binary data directly; they must be encode
-ed explicitly with a specific encoding.
For the technical definition, see the Python 3 glossary:
An object that supports the Buffer Protocol and can export a C-contiguous buffer. This includes all
bytes
,bytearray
, andarray.array
objects, as well as many commonmemoryview
objects. Bytes-like objects can be used for various operations that work with binary data; these include compression, saving to a binary file, and sending over a socket.Some operations need the binary data to be mutable. The documentation often refers to these as “read-write bytes-like objects”. Example mutable buffer objects include
bytearray
and amemoryview
of abytearray
. Other operations require the binary data to be stored in immutable objects (“read-only bytes-like objects”); examples of these includebytes
and amemoryview
of abytes
object.