Skip to content

Commit

Permalink
simplify group access to avoid recursion; test missing group error
Browse files Browse the repository at this point in the history
  • Loading branch information
alimanfoo committed May 14, 2014
1 parent 13b118c commit b1ae839
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 19 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ nosetests.xml
.project
.pydevproject

# PyCharm
.idea

# xray specific
doc/_build
doc/generated
Expand Down
6 changes: 6 additions & 0 deletions test/test_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,12 @@ def test_open_group(self):
actual = open_dataset(tmp_file, group=group)
self.assertVariableEqual(actual['x'], expected['x'])

# check that missing group raises appropriate exception
try:
open_dataset(tmp_file, group='bar')
except IOError:
pass # expected

def test_open_subgroup(self):
# Create a netCDF file with a dataset stored within a group within a group
with create_tmp_file() as tmp_file:
Expand Down
30 changes: 11 additions & 19 deletions xray/backends/netCDF4_.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,30 +63,22 @@ def _nc4_values_and_dtype(variable):


def _nc4_group(ds, group):
if group in {None, '', '/'}:
if group in set([None, '', '/']):
# use the root group
return ds
else:
# make sure it's a string (maybe should raise an error if not?)
group = str(group)
# make sure it's a string
if not isinstance(group, basestring):
raise ValueError('group must be a string or None')
# support path-like syntax
path = group.strip('/').split('/')
# find the specified group by recursive search
return _nc4_group_from_path(ds, path)


def _nc4_group_from_path(parent, path):
key = path[0]
path = path[1:]
if key not in parent.groups:
raise IOError('group not found: %r, %s' % (parent, key))
else:
parent = parent.groups[key]
if len(path) > 0:
# recurse
return _nc4_group_from_path(parent, path)
else:
return parent
for key in path:
try:
ds = ds.groups[key]
except KeyError as e:
# wrap error to provide slightly more helpful message
raise IOError('group not found: %s' % key, e)
return ds


class NetCDF4DataStore(AbstractWritableDataStore):
Expand Down

0 comments on commit b1ae839

Please sign in to comment.