Skip to content

Instantly share code, notes, and snippets.

@alexland
Created January 30, 2015 03:33
Show Gist options
  • Save alexland/0f4810b7d12414d96f86 to your computer and use it in GitHub Desktop.
Save alexland/0f4810b7d12414d96f86 to your computer and use it in GitHub Desktop.
typed memoryviews in NumPy using the python buffer protocol (PEP 3118)
import numpy as NP
d = NP.random.randint(1, 10, 40).reshape(8, 5)
mv = memoryview(d)
def mem_addr(arr):
'''
returns: location of a NumPy array in memory, or
more precisely, a pointer to the first item in array
pass in: a NumPy array
'''
return arr.__array_interface__['data'][0]
# two arrays w/ the same memory location share a common data buffer;
# however because the value returned from mem_attr is just a pointer
# to the first item in the array, mem_attr does not know if one
# array is a slice of another, eg, a vs a[:5]
# to identify that case, use the fn below:
# from the book on IPython by Cyrille Rossant (http://ipython-books.github.io/featured-01/):
def get_data_buffer(arr):
base = arr
while isinstance(base.base, NP.ndarray):
base = base.base
return base
def arrays_share_same_buffer(arr1, arr2):
return get_data_bufffer(arr1) is get_data_buffer(arr2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment