Scribbling

Python: Memoryview function 본문

Computer Science/Python

Python: Memoryview function

focalpoint 2022. 3. 23. 11:51

 

Python memoryview function returns memory view objects.

 

So why use it? Memory view is a safe way to expose 'buffer protocol' in python. Buffer protocol allows an object to expose its inner data without copying. As buffer protocol is only available at the C-API level, memoryview is present to expose the same protocol at Python level.

 

Example1: how memoryview works

arr = bytearray('XYZ', 'utf-8')
mv = memoryview(arr)

print(mv[0])
print(bytes(mv[0:1]))

 

Example2: how to modify internal data using memoryview

arr = bytearray('XYZ', 'utf-8')
mv = memoryview(arr)

print(arr)
mv[0] = 68
print(arr)
str = str(mv)
bt = bytes(mv)

print(str)
print(bt)

https://www.geeksforgeeks.org/memoryview-in-python/

 

memoryview() in Python - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

 

'Computer Science > Python' 카테고리의 다른 글

Python: Decorator & Closure  (0) 2022.03.29
Python: Design Patterns  (0) 2022.03.25
Python Immutable Dictionary, Set  (0) 2022.03.22
Python Data Structures: Sequences  (0) 2022.03.21
Python Magic Methods: Pythonic Data Model  (0) 2022.03.16