Created
January 30, 2015 03:33
-
-
Save alexland/0f4810b7d12414d96f86 to your computer and use it in GitHub Desktop.
typed memoryviews in NumPy using the python buffer protocol (PEP 3118)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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