[Numpy-discussion] test if two arrays share the same data
Sun Sep 5 16:53:02 CDT 2010
2010/9/5 Ernest Adrogué <email@example.com>:
> 5/09/10 @ 15:59 (-0500), thus spake Robert Kern:
>> 2010/9/5 Ernest Adrogué <firstname.lastname@example.org>:
>> > 5/09/10 @ 21:25 (+0200), thus spake Gael Varoquaux:
>> >> On Sun, Sep 05, 2010 at 09:12:34PM +0200, Ernest Adrogué wrote:
>> >> > Hi,
>> >> > How can it be done?
>> >> np.may_share_memory
>> > Thanks Gael and Puneeth.
>> > I think the .base attribute is enough for what I want.
>> No, you really want may_share_memory().
> Ok, I trust you :)
Just to elaborate, one of the problems is that .base gives only the
direct ancestor of the current array:
In : a = np.arange(10)
In : b = a[:]
In : c = b[:]
In : c.base
Out: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In : c.base is b
In : c.base is a
To check whether the arrays use the same memory arena, you have to
walk the chain all the way back to the original base array.
may_share_memory does this, and checks whether the arrays use
overlapping ranges of memory as well. (It's "may" because you can have
things like one being the even elements and the other being the odd
elements, but checking for this is highly nontrivial, so
may_share_memory just returns True.)
P.S. if you're thinking that this definition of base can cause memory
leaks, then yes, you're right, but they are leaks only of the array
descriptor objects, not the underlying memory. Still, you can exhaust
memory doing things like:
a = np.arange(10)
a = a[:]
So don't do that. -A
> NumPy-Discussion mailing list
More information about the NumPy-Discussion