Skip to content

Commit

Permalink
ENH: Add ability to access datasets by index (Fixes Unidata#134)
Browse files Browse the repository at this point in the history
When getting an item by string, work as before. For all else, treat as
an index into values. Works for catalog refs as well.
  • Loading branch information
dopplershift committed Jul 19, 2017
1 parent 4bee767 commit b924314
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
15 changes: 13 additions & 2 deletions siphon/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,17 @@
log.setLevel(logging.ERROR)


class IndexableMapping(OrderedDict):
"""Extend ``OrderedDict`` to allow index-based access to values."""
def __getitem__(self, item):
"""Return an item either by index or name."""
try:
item + '' # Raises if item not a string
return super().__getitem__(item)
except TypeError:
return list(self.values())[item]


class TDSCatalog(object):
"""
Parse information from a THREDDS Client Catalog.
Expand Down Expand Up @@ -79,9 +90,9 @@ def __init__(self, catalog_url):
root = ET.fromstring(resp.text)
self.catalog_name = root.attrib.get('name', 'No name found')

self.datasets = OrderedDict()
self.datasets = IndexableMapping()
self.services = []
self.catalog_refs = OrderedDict()
self.catalog_refs = IndexableMapping()
self.metadata = {}
self.ds_with_access_elements_to_process = []
service_skip_count = 0
Expand Down
11 changes: 11 additions & 0 deletions siphon/tests/test_catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,17 @@ def test_datasets_order():
'Latest Collection for NAM CONUS 20km']


@recorder.use_cassette('top_level_20km_rap_catalog')
def test_datasets_get_by_index():
"""Test that datasets can be accessed by index."""
url = ('http://thredds.ucar.edu/thredds/catalog/grib/NCEP/NAM/'
'CONUS_20km/noaaport/catalog.xml')
cat = TDSCatalog(url)
assert cat.datasets[0].name == 'Full Collection (Reference / Forecast Time) Dataset'
assert cat.datasets[1].name == 'Best NAM CONUS 20km Time Series'
assert cat.datasets[2].name == 'Latest Collection for NAM CONUS 20km'


@recorder.use_cassette('top_level_cat')
def test_catalog_ref_order():
"""Test that catalog references are properly ordered."""
Expand Down

0 comments on commit b924314

Please sign in to comment.