@@ -661,30 +661,38 @@ def get_end(self, annotation: Annotation) -> Union[int, float]:
661
661
def __getitem__ (self , item : str ) \
662
662
-> Union [Document , View , Annotation , MmifMetadata , DocumentsList , ViewsList ]:
663
663
"""
664
- getitem implementation for Mmif. When nothing is found, this will raise an error
665
- rather than returning a None (although pytype doesn't think so...)
664
+ getitem implementation for Mmif. This will try to find any object, given an identifier or an immediate
665
+ attribute name. When nothing is found, this will raise an error rather than returning a None
666
666
667
667
:raises KeyError: if the item is not found or if the search results are ambiguous
668
- :param item: the search string, a document ID, a view ID, or a view-scoped annotation ID
668
+ :param item: an attribute name or an object identifier (a document ID, a view ID, or an annotation ID). When
669
+ annotation ID is given as a "short" ID (without view ID prefix), the method will try to find a
670
+ match from the first view, and return immediately if found.
669
671
:return: the object searched for
672
+ :raise KeyError: if the item is not found or multiple objects are found with the same ID
670
673
"""
671
674
if item in self ._named_attributes ():
672
675
return self .__dict__ [item ]
673
676
split_attempt = item .split (self .id_delimiter )
674
677
675
- document_result = self .documents .get (split_attempt [0 ])
676
- view_result = self .views .get (split_attempt [0 ])
678
+ found = []
677
679
678
680
if len (split_attempt ) == 1 :
679
- anno_result = None
680
- elif view_result :
681
- anno_result = view_result [split_attempt [1 ]]
681
+ found .append (self .documents .get (split_attempt [0 ]))
682
+ found .append (self .views .get (split_attempt [0 ]))
683
+ for view in self .views :
684
+ found .append (view .annotations .get (split_attempt [0 ]))
685
+ elif len (split_attempt ) == 2 :
686
+ v = self .get_view_by_id (split_attempt [0 ])
687
+ if v is not None :
688
+ found .append (v .annotations .get (split_attempt [1 ]))
682
689
else :
683
690
raise KeyError ("Tried to subscript into a view that doesn't exist" )
691
+ found = [x for x in found if x is not None ]
684
692
685
- if view_result and document_result :
693
+ if len ( found ) > 1 :
686
694
raise KeyError ("Ambiguous ID search result" )
687
- if not ( view_result or document_result ) :
695
+ elif len ( found ) == 0 :
688
696
raise KeyError ("ID not found: %s" % item )
689
- return anno_result or view_result or document_result
690
-
697
+ else :
698
+ return found [ - 1 ]
0 commit comments