memoryview() Built-in Function


Python - memoryview()

Python memoryview() built-in function is used to get the memory view object that allows you to view the contents of a bytes-like object as a sequence of machine values.

memoryview() built-in function can be used for efficient data manipulation, sharing memory between objects, interacting with C code, etc.

In this tutorial, you will learn the syntax and usage of memoryview() built-in function, and cover some examples.

Syntax

The syntax of memoryview() function is

memoryview(object)

where

ParameterDescription
objectA bytes-like object. e.g., bytes, bytearray, or another memory view object.

Examples

1. Get memory view of bytes object

In the following program, we take a bytes object, and get a memoryview object for this bytes object.

Python Program

data = bytearray(b'hello world')

# Get memory view of data
mv = memoryview(data)
print(mv)

Output

<memory at 0x104725d80>

2. Slice memoryview

memoryview supports slicing. In the following program, we slice the memoryview object, and print it to standard output.

Python Program

data = bytearray(b'hello world')

# Get memory view of data
mv = memoryview(data)
# Slice memoryview
mvslice = mv[2:8]
print(bytes(mvslice))

Output

b'llo wo'

Uses of memoryview()

memoryview() built-in function can be used for the following purposes.

  • Efficient data manipulation: By using memoryview() on a bytes-like object, you can efficiently manipulate the data as a sequence of machine values. This can be faster than copying the data into a new object or converting it to a different data type.
  • Sharing memory between objects: Since memoryview() returns a view of the data rather than a new object, it can be used to share memory between different parts of your code. For example, you could create a memory view of a large bytes-like object and pass it to a function that only needs to access a small portion of the data.
  • Interacting with C code: The memoryview() function can be useful when interacting with C code that operates on raw memory. You can pass a memory view object to a C function that expects a pointer to memory, allowing you to access and manipulate the data in Python and C code.

Summary

In this Built-in Functions tutorial, we learned the syntax of the memoryview() built-in function, and how to use this function to create a memoryview for a bytes-like object.