6

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?

Daniel Walker
6,9587 gold badges25 silver badges68 bronze badges
asked Oct 15, 2017 at 0:34

1 Answer 1

7

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.

answered Oct 15, 2017 at 0:37
Sign up to request clarification or add additional context in comments.

4 Comments

It is worth mentioning that the string could be converted to bytes
@YaroslavSurzhikov: Added a note on that.
@ShadowRanger So, for example, if I was to use a json string in base64.b64encode(), how would I change the string to a bytes-like object?
@RayAntebioni: Typically JSON is represented as UTF-8, so you'd pass jsonstring.encode('utf-8').

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.