Open In App

memoryview() in Python

Last Updated : 30 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python memoryview() function returns the memory views objects. Before learning more about memoryview() function let’s see why do we use this function.

Why do we use memoryview() function? 

As Memory view is a safe way to expose the buffer protocol in Python and a memoryview behaves just like bytes in many useful contexts (for example, it supports the mapping protocol) so it provides an adequate replacement if used carefully. The great thing about it is that it uses the buffer protocol beneath the covers to avoid copies and just juggle pointers to data. So before we get into what memory views, we need to first understand Buffer Protocol.

Buffer Protocol

Buffer protocol provides a way to access the internal data of an object. This internal data is a memory array or a buffer. It allows one object to expose its internal data (buffers) and the other to access those buffers without intermediate copying. Buffer protocol is only accessible to us at the C-API level and not using our normal codebase. So, to expose the same protocol to a normal Python codebase, memory views are present.

Memory view

memoryview objects allow Python code to access the internal data of an object that supports the buffer protocol without copying. The memoryview() function allows direct read and write access to an object’s byte-oriented data without needing to copy it first. That can yield large performance gains when operating on large objects since it doesn’t create a copy when slicing.

memoryview() Function in Python

Syntax: memoryview(obj)

Parameters:

  • obj – object whose internal data is to be exposed.
  • supporting buffer protocol – str and bytearray (but not unicode).

Return Value: Returns a memoryview object.

Python memoryview() Function Example

We use memoryview() function to get a memory view in Python. Below are some examples:

Example 1: Python memoryview() works

This example initializes a byte array with UTF-8 encoded characters, creates a memory view of that byte array, and then demonstrates how to access and convert individual bytes from the memory view.

Python3




byte_array = bytearray('XYZ', 'utf-8')
 
mv = memoryview(byte_array)
 
print(mv[0])
print(bytes(mv[0:1]))


Output

88
b'X'


Example 2: Modify internal data using memoryview

In this example, we are using memoryview() in Python to demonstrate how memory views can be used to access and modify the internal data of a bytearray in a memory-efficient manner.

Python3




# Python program to illustrate
# Modifying internal data using memory view
 
# random bytearray
byte_array = bytearray('XYZ', 'utf-8')
print('Before update:', byte_array)
 
mem_view = memoryview(byte_array)
 
# update 2nd index of mem_view to J
mem_view[2] = 74
print('After update:', byte_array)


Output

Before update: bytearray(b'XYZ')
After update: bytearray(b'XYJ')


Explanation how we modify internal data in above program : Here, we updated the memory view’s 2nd index to ASCII value as 74 (J). In this memoryview object mem_view references the same buffer or memory and updating the index in mem_view and it also updates byte_array.

Example 3: Python memoryview() to bytes

The below example initializes a bytearray, creates a memory view of it, and then demonstrates how to convert that memory view to a bytes object.

Python3




# Python program to illustrate memory view
 
# random bytearray
byte_array = bytearray('XYZ', 'utf-8')
 
mem_view = memoryview(byte_array)
print(type(mem_view))
 
byt = bytes(mem_view)
print(type(byt))


Output

<class 'memoryview'>
<class 'bytes'>


Example 4: Python memoryview() to string

This example code initializes a bytearray, creates a memory view of it, and then attempts to convert the memory view to a string.

Python3




# Python program to illustrate memory view
 
# random bytearray
byte_array = bytearray('XYZ', 'utf-8')
 
mem_view = memoryview(byte_array)
print(type(mem_view))
 
string = str(mem_view)
print(type(string))


Output

<class 'memoryview'>
<class 'str'>


Importance of buffer protocol and memory views

By using buffer protocol we can work on large data like we want to work on binary data of an image. Buffer protocol, can create another object access to modify the large data without copying it. This makes the program use less memory and increases the execution speed.



Previous Article
Next Article

Similar Reads

Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
Python | Visualizing O(n) using Python
Introduction Algorithm complexity can be a difficult concept to grasp, even presented with compelling mathematical arguments. This article presents a tiny Python program that shows the relative complexity of several typical functions. It can be easily adapted to other functions. Complexity. Why it matters? Computational complexity is a venerable su
3 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
Python | Convert list to Python array
Sometimes while working in Python we can have a problem in which we need to restrict the data elements to just one type. A list can be heterogeneous, can have data of multiple data types and it is sometimes undesirable. There is a need to convert this to a data structure that restricts the type of data. Convert List to Array PythonBelow are the met
3 min read
Practice Tags :