MemoryView

MemoryView enable slicing action in bytearray and str WILL NOT return a new object.

Given bytearray is mutable and stris immutable, only bytearray can update the value.

>> a = 'aaaaaa'
>> b = a[:2]    # Create a new string object

>> a = bytearray('aaaaaa')
>> b = a[:2]    # Create a new bytearray object
>> b[:2] = 'bb' # The modification on b does not affect a
>> a
bytearray(b'aaaaaa')
>> b
bytearray(b'bb')

Applying MemoryView

>> a = 'aaaaaa'
>> ma = memoryview(a)
>> ma.readonly  # Read-only MemoryView
True
>> mb = ma[:2]  # Will not create a new String object

>> a = bytearray('aaaaaa')
>> ma = memoryview(a)
>> ma.readonly  # Writable MemoryView
False
>> mb = ma[:2]      # Will not create a new bytearray
>> mb[:2] = 'bb'    # Modification on mb will not affect ma
>> mb.tobytes()
'bb'
>> ma.tobytes()
'bbaaaa'

Last updated

Was this helpful?