Python
  • Initial page
  • Skills & Concept
    • Function
    • Generator
    • Class
    • Asyncio
    • Interface
    • Decorator
    • Maxin
    • Abstract Base Class
    • MemoryView
  • Magic methods
    • What is Magic Methods?
  • Data Structure
    • Data Structure in Python
    • List & Tuple
    • Named Tuples
    • Slicing in Sequence
    • Queue & Dequeue
    • Ordered Dict
    • Linked list
  • Writing Test Case
    • How to write Test case
    • Testing a Flask End-point
  • Libraries
    • Flask and Gunicorn
      • Flask JWT
      • Flask Limiter
      • Flask Rest
Powered by GitBook
On this page

Was this helpful?

  1. Skills & Concept

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'
PreviousAbstract Base ClassNextWhat is Magic Methods?

Last updated 6 years ago

Was this helpful?