Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Forward slicing in DataIO #141

Merged
merged 8 commits into from
Sep 26, 2019
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -574,6 +584,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()