{"id":24576,"date":"2021-10-22T09:05:34","date_gmt":"2021-10-22T03:35:34","guid":{"rendered":"https:\/\/python-programs.com\/?p=24576"},"modified":"2021-11-05T19:42:55","modified_gmt":"2021-11-05T14:12:55","slug":"python-memoryview-function-with-examples","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-memoryview-function-with-examples\/","title":{"rendered":"Python memoryview() Function with Examples"},"content":{"rendered":"

In the previous article, we have discussed Python Program for ord() Function<\/a>
\nThe memoryview() function in Python returns memory views objects. Before delving deeper into the memoryview() function, consider why we use it.<\/p>\n

Why are we using the memoryview() function?<\/strong>
\nBecause Memory view is a safe way to expose the buffer protocol in Python and a memoryview behaves like bytes in many useful contexts (for example, it supports the mapping protocol), it can serve as an adequate replacement if used correctly. The best part is that it uses the buffer protocol under the hood to avoid copies and simply juggle pointers to data. So, before we get into what memory views are available, we must first understand the Buffer Protocol.<\/p>\n

What is buffer protocol?<\/strong><\/p>\n

The buffer protocol allows you to access an object’s internal data. This internal data is in the form of a memory array or a buffer. It enables one object to expose its internal data (buffers) and another to access those buffers without requiring intermediate copying. The buffer protocol is only available to us at the C-API level, not through our normal codebase. Memory views are used to expose the same protocol to a standard Python codebase.<\/p>\n

Memoryview<\/strong><\/p>\n

Memoryview objects enable Python code to access the internal data of an object that supports the buffer protocol without the need for copying. The memoryview() function provides direct read and write access to byte-oriented data in an object without the need to copy it first. Because it does not create a copy when slicing, this can result in significant performance gains when working with large objects.<\/p>\n

Syntax:<\/strong><\/p>\n

memoryview(object)<\/pre>\n

Parameters<\/strong><\/p>\n

object: The object whose internal data will be exposed.
\nbuffer protocol support \u2013 str and bytearray (but not Unicode).<\/p>\n

Return Value:<\/strong><\/p>\n

A memoryview object is returned.<\/p>\n

Examples:<\/strong><\/p>\n

Example1:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given String = 'EFG'<\/pre>\n

Output:<\/strong><\/p>\n

69\r\nb'EFG'\r\n[69, 70, 71]<\/pre>\n

Example2:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given String = 'uvw'<\/pre>\n

Output:<\/strong><\/p>\n

117\r\nb'uvw'\r\n[117, 118, 119]<\/pre>\n

Program for memoryview() Function in Python<\/h2>\n