memoryview()

The built-in memoryview() function provides a way to access the internal data of an object that supports the buffer protocol without copying it. It’s particularly useful for efficiently manipulating large datasets or interfacing with binary data:

Python
>>> image = bytearray([0, 127, 255, 64])
>>> mv = memoryview(image)
>>> mv[0]
0

memoryview() Signature

Python Syntax
memoryview(object)

Arguments

Argument Description
object An object supporting the buffer protocol, such as bytes, bytearray, or array.array.

Return Value

  • Returns a memoryview object, which allows for efficient access to the data without copying it.

memoryview() Examples

With a bytearray as an argument:

Python
>>> data = bytearray(b"Hello")
>>> mv = memoryview(data)
>>> mv[1] = ord("a")
>>> bytes(mv)
b'Hallo'

With a bytes object as an argument:

Python
>>> data = bytes(b"World")
>>> mv = memoryview(data)
>>> mv[0]  # ASCII for W
87

memoryview() Common Use Cases

The most common use cases for the memoryview() function include:

  • Accessing and manipulating slices of large datasets without copying them
  • Interfacing with C extensions or libraries that require buffer protocol support
  • Performing efficient operations on binary data, like image processing or data serialization

memoryview() Real-World Example

Suppose you have a bytearray representing pixel data of an image, and you want to invert the pixel values efficiently. You can use the memoryview() function:

Python
>>> image = bytearray([0, 127, 255, 64, 128, 192, 32, 96, 160])
>>> mv = memoryview(image)

>>> for i in range(len(mv)):
...     mv[i] = 255 - mv[i]
...

>>> list(mv)
[255, 128, 0, 191, 127, 63, 223, 159, 95]

In this example, the memoryview object allows you to invert the pixel values directly, reflecting the changes on the original bytearray. This approach is memory-efficient and fast because it avoids unnecessary data copying.

Tutorial

Python's Built-in Functions: A Complete Exploration

In this tutorial, you'll learn the basics of working with Python's numerous built-in functions. You'll explore how to use these predefined functions to perform common tasks and operations, such as mathematical calculations, data type conversions, and string manipulations.

basics python

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


By Leodanis Pozo Ramos • Updated Nov. 12, 2024 • Reviewed by Dan Bader