Skip to content

Commit

Permalink
Forward slicing in DataIO (#141)
Browse files Browse the repository at this point in the history
* Forward slicing in DataIO 
* Fix #144 by adding copy/deepcopy to DataIO
* Add testing for DataIO
  • Loading branch information
oruebel authored Sep 26, 2019
1 parent 7705c59 commit dc07c3e
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/hdmf/data_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import numpy as np
from warnings import warn
from six import with_metaclass, text_type, binary_type
import copy

from .container import Data, DataRegion
from .utils import docval, getargs, popargs, docval_macro, get_data_shape
Expand Down Expand Up @@ -563,6 +564,15 @@ def __init__(self, **kwargs):
def data(self):
return self.__data

def __copy__(self):
newobj = DataIO(data=self.data)
return newobj

def __deepcopy__(self, memo):
result = DataIO(data=copy.deepcopy(self.__data))
memo[id(self)] = result
return result

def __len__(self):
if not self.valid:
raise InvalidDataIOError("Cannot get length of data. Data is not valid.")
Expand All @@ -577,6 +587,12 @@ def __getattr__(self, attr):
raise InvalidDataIOError("Cannot get attribute '%s' of data. Data is not valid." % attr)
return getattr(self.data, attr)

def __getitem__(self, item):
"""Delegate slicing to the data object"""
if not self.valid:
raise InvalidDataIOError("Cannot get item from data. Data is not valid.")
return self.data[item]

def __array__(self):
"""
Support conversion of DataIO.data to a numpy array. This function is
Expand Down
39 changes: 39 additions & 0 deletions tests/unit/utils_test/test_core_DataIO.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import unittest2 as unittest

from hdmf.data_utils import DataIO
import numpy as np
from copy import copy, deepcopy


class DataIOTests(unittest.TestCase):

def setUp(self):
pass

def tearDown(self):
pass

def test_copy(self):
obj = DataIO(data=[1., 2., 3.])
obj_copy = copy(obj)
self.assertNotEqual(id(obj), id(obj_copy))
self.assertEqual(id(obj.data), id(obj_copy.data))

def test_deepcopy(self):
obj = DataIO(data=[1., 2., 3.])
obj_copy = deepcopy(obj)
self.assertNotEqual(id(obj), id(obj_copy))
self.assertNotEqual(id(obj.data), id(obj_copy.data))

def test_dataio_slice_delegation(self):
indata = np.arange(30)
dset = DataIO(indata)
self.assertTrue(np.all(dset[2:15] == indata[2:15]))

indata = np.arange(50).reshape(5, 10)
dset = DataIO(indata)
self.assertTrue(np.all(dset[1:3, 5:8] == indata[1:3, 5:8]))


if __name__ == '__main__':
unittest.main()

0 comments on commit dc07c3e

Please sign in to comment.