Skip to content

Commit 425ce84

Browse files
author
Steve Canny
committed
add dict-style lookup on rId to RelationshpCollctn
1 parent 62b42ce commit 425ce84

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

opc/package.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -140,9 +140,18 @@ def __init__(self, baseURI):
140140
self._baseURI = baseURI
141141
self._rels = []
142142

143-
def __getitem__(self, idx):
144-
"""Implements access by subscript, e.g. rels[9]"""
145-
return self._rels.__getitem__(idx)
143+
def __getitem__(self, key):
144+
"""
145+
Implements access by subscript, e.g. ``rels[9]``. It also implements
146+
dict-style lookup of a relationship by rId, e.g. ``rels['rId1']``.
147+
"""
148+
if isinstance(key, basestring):
149+
for rel in self._rels:
150+
if rel.rId == key:
151+
return rel
152+
raise KeyError("no rId '%s' in RelationshipCollection" % key)
153+
else:
154+
return self._rels.__getitem__(key)
146155

147156
def __len__(self):
148157
"""Implements len() built-in on this object"""

tests/test_package.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,19 @@ def it_supports_indexed_access(self):
152152
except IndexError:
153153
pass
154154

155+
def it_has_dict_style_lookup_of_rel_by_rId(self):
156+
rel = Mock(name='rel', rId='foobar')
157+
rels = RelationshipCollection(None)
158+
rels._rels.append(rel)
159+
assert rels['foobar'] == rel
160+
161+
def it_should_raise_on_failed_lookup_by_rId(self):
162+
rel = Mock(name='rel', rId='foobar')
163+
rels = RelationshipCollection(None)
164+
rels._rels.append(rel)
165+
with pytest.raises(KeyError):
166+
rels['barfoo']
167+
155168
def it_can_add_a_relationship(self, _Relationship_):
156169
baseURI, rId, reltype, target, external = (
157170
'baseURI', 'rId9', 'reltype', 'target', False

0 commit comments

Comments
 (0)