8000 ENH: Make memmaps return arrays in ufuncs and fancy indexing · seberg/numpy@d86c8bd · GitHub
[go: up one dir, main page]

Skip to content

Commit d86c8bd

Browse files
committed
ENH: Make memmaps return arrays in ufuncs and fancy indexing
This makes memmeps return an array instead of a memmap instance for fancy indexing or ufuncs, etc. that use __array_wrap__ and __array_prepare__. The type is preserved for subclasses however. Also copy is one example that still returns a memmap even if it does not point to the same memory.
1 parent 27690e3 commit d86c8bd

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

numpy/core/memmap.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,27 @@ def __array_finalize__(self, obj):
282282
self.offset = None
283283
self.mode = None
284284

285+
def __array_wrap__(self, arr, context=None):
286+
# If the type is not memmap, then a user subclass may have some special
287+
# functions that should be preserved to avoid a regression
288+
if type(self) is not memmap:
289+
return arr.view(type=type(self))
290+
return arr
291+
292+
def __array_prepare__(self, arr, context=None):
293+
if type(self) is not memmap:
294+
return arr.view(type=type(self))
295+
# There is no use in making an array a memmap, since it does not own
296+
# its memory.
297+
return arr
298+
299+
def __getitem__(self, index):
300+
# return an array if the result does not point to self's memory
301+
res = super(memmap, self).__getitem__(index)
302+
if type(res) is memmap and res._mmap is None:
303+
return res.view(ndarray)
304+
return res
305+
285306
def flush(self):
286307
"""
287308
Write any changes in the array to the file on disk.

numpy/core/tests/test_memmap.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import os
44

55
from numpy import memmap
6-
from numpy import arange, allclose, asarray
6+
from numpy import arange, allclose, asarray, add
77
from numpy.testing import *
88

99
class TestMemmap(TestCase):
@@ -115,5 +115,20 @@ def test_view(self):
115115
new_array = asarray(fp)
116116
assert(new_array.base is fp)
117117

118+
def test_to_array_conversions(self):
119+
class MMSubclass(memmap):
120+
pass
121+
m = memmap(self.tmpfp, dtype=self.dtype, shape=self.shape)
122+
r = m + 1
123+
assert_(not isinstance(r, memmap))
124+
add(m, 1, out=m)
125+
assert_(isinstance(m, memmap))
126+
assert_(not isinstance(m[:,[0,1]], memmap))
127+
# But for subclasses, preserve in case someone tagged on functions:
128+
m = MMSubclass(self.tmpfp, dtype=self.dtype, shape=self.shape)
129+
r = m + 1
130+
assert_(isinstance(r, MMSubclass))
131+
assert_(isinstance(m[:,[0,1]], MMSubclass))
132+
118133
if __name__ == "__main__":
119134
run_module_suite()

0 commit comments

Comments
 (0)
0