[Numpy-discussion] test if two arrays share the same data
Anne Archibald
aarchiba@physics.mcgill...
Sun Sep 5 16:53:02 CDT 2010
2010/9/5 Ernest Adrogué <eadrogue@gmx.net>:
> 5/09/10 @ 15:59 (-0500), thus spake Robert Kern:
>> 2010/9/5 Ernest Adrogué <eadrogue@gmx.net>:
>> > 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 [2]: a = np.arange(10)
In [3]: b = a[:]
In [4]: c = b[:]
In [5]: c.base
Out[5]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [6]: c.base is b
Out[6]: True
In [7]: c.base is a
Out[7]: False
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.)
Anne
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)
while True:
a = a[:]
So don't do that. -A
> Ernest
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
More information about the NumPy-Discussion
mailing list