Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python memoryview() Function

Python memoryview() Function

Python3 Built-in Functions Python3 built-in function


memoryview() is a built-in Python function that creates a memory view.

memoryview returns a "memory view" object that allows Python code to access an object's internal data buffer without copying the data. This can improve performance when handling large binary data.

Word meaning: memoryview means "memory view", an object for accessing data buffers.


Basic syntax and parameters

Syntax format


memoryview(obj)

Parameter Description

- Type: an object implementing the buffer protocol (such as bytes or bytearray) - Description: the object for which to create a memory view.

Function description


Example

Example 1: creating a memoryview

Example

Create from a bytearray

data

=

bytearray

(

b

"Hello"

)

m

=

memoryview

(

data

)

print

(

m

)

         

Output:

Create from bytes

data

=

b

"World"

m

=

memoryview

(

data

)

print

(

m

[

0

]

)

     

Output: 87 (the ASCII code of W)

Access multiple bytes

print

(

m

[

0

:

3

]

)

   

Output:

Expected output:


87

Code analysis:

  1. A memoryview can be created from bytes or bytearray.
  2. It supports indexing and slicing.

Example 2: modifying data (mutable objects only)

Example

memoryview can modify the underlying data directly

data

=

bytearray

(

b

"Hello"

)

m

=

memoryview

(

data

)

Modify the underlying data

m

[

0

]

=

74

 

'J'

print

(

data

)

 

Output: bytearray(b'Jello')

Slice modification

m

[

1

:

5

]

=

b

"abcd"

print

(

data

)

 

Output: bytearray(b'Jabcd')

C type format

data

=

b

"\x01\x02\x03\x04"

m

=

memoryview

(

data

)

print

(

m.

tobytes

(

)

)

 

Output: b'\x01\x02\x03\x04'

Expected output:

bytearray(b'Jello')
bytearray(b'Jabcd')
b'\x01\x02\x03\x04'

memoryview allows direct modification of the underlying data, which is very efficient for handling large binary data.


Python3 Built-in Functions Python3 built-in function