Skip to content

bytes-like object

In Python, a bytes-like object is any object that supports the buffer protocol and can expose its underlying binary data as a C-contiguous buffer. This protocol allows an object to share its binary data with other objects efficiently, without copying.

Historically, only C extension types could implement the buffer protocol, but since Python 3.12 a pure-Python class can also become a bytes-like object by defining __buffer__() and __release_buffer__().

Bytes-like objects include all bytes, bytearray, and array.array objects, as well as many common memoryview objects and other objects in Python’s standard library that expose binary data through the buffer protocol.

Not every memoryview qualifies. A view over a non-C-contiguous buffer can’t export the C-contiguous buffer that bytes-like APIs require.

Bytes-like objects are useful when you’re working with binary data, such as reading from or writing to files in binary mode, handling network data, or processing images. They allow you to efficiently manipulate binary data without needing to convert it to other data types, which can be both time-consuming and memory-intensive.

Python also distinguishes between read-only bytes-like objects, such as bytes and a memoryview of a bytes object, and read-write (mutable) bytes-like objects, such as bytearray and a memoryview of a bytearray. Some APIs require mutable buffers, while others accept either kind, so check the docstring when you see an error message like “a bytes-like object is required.”

Example

Here’s an example that demonstrates how to use bytes-like objects in Python:

Language: Python
>>> # Example with bytes
>>> byte_data = b"Hello, Real Python!"
>>> byte_data
b'Hello, Real Python!'

>>> # Example with bytearray
>>> byte_array_data = bytearray(b"Hello, Real Python!")
>>> byte_array_data[7:11] = b"World"
>>> byte_array_data
bytearray(b'Hello, World Python!')

>>> # Example with memoryview
>>> byte_data = b"Hello, Real Python!"
>>> memory_view = memoryview(byte_data)
>>> memory_view[7:11].tobytes()
b'Real'

In this example, you see how bytes, bytearray, and memoryview objects can handle binary data in Python.

Bytes Objects: Handling Binary Data in Python

Tutorial

Bytes Objects: Handling Binary Data in Python

In this tutorial, you'll learn about Python's bytes objects, which help you process low-level binary data. You'll explore how to create and manipulate byte sequences in Python and how to convert between bytes and strings. Additionally, you'll practice this knowledge by coding a few fun examples.

intermediate python

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Sept. 23, 2026 • Reviewed by Dan Bader