[Numpy-discussion] detecting shared data

Bill Baxter wbaxter@gmail....
Wed Apr 11 18:34:18 CDT 2007

On 4/12/07, Matthew Koichi Grimes <mkg@cs.nyu.edu> wrote:
> It's better than nothing. I basically want some sanity-check assert code
> that can assert that some arrays are in fact sub-arrays of another
> array. Your OWNDATA suggestion meets me halfway by allowing me to check
> that these sub-arrays are at least sub-arrays of *someone*.
> Thanks,
> -- Matt
> Pierre GM wrote:
> > On Wednesday 11 April 2007 18:12:16 Matthew Koichi Grimes wrote:
> >
> >> Is there any way to detect whether one array is a view into another
> >>
> >> array? I'd like something like:
> >>  >>> arr = N.arange(5)
> >>  >>> subarr = arr[1:3]
> >>  >>> sharesdata(arr, subarr)
> >>
> >
> > Mmh, would arr.flags['OWNDATA'] would do the trick ?
> > p.

I wrote this a while back that may do what you want:

def same_array(a, b):
    """Tries to figure out if a and b are sharing (some of) the same
memory or not.
    This is sometimes useful for determining if a copy was made as a
result of some
    operation, or for determining if modifying a might also modify b.
    A True result means that a and b both borrow memory from the same
array object,
    but it does not necessarily mean the memory regions used overlap.
For example:
    >>> x = rand(4,4)
    >>> a,b = x[:2], x[2:]
    >>> same_array(a,b)
    A False result means the arrays definitely do not overlap in memory.
    same_array(a, b) -> Bool
    ab = a
    while ab.base is not None:
        ab = ab.base
    bb = b
    while bb.base is not None:
        bb = bb.base
    return ab is bb

But maybe that's pretty much what may_share_memory does?

More information about the Numpy-discussion mailing list