@@ -59,26 +59,46 @@ def check_if_in_original(self, tag_or_group):
5959
6060 return self ._check_in_group (tag_or_group , final_list )
6161
62- def replace (self , item_to_replace , new_contents ):
62+ @staticmethod
63+ def replace (item_to_replace , new_contents ):
6364 """ Replace an existing tag or group.
6465
66+ Note: This is a static method that relies on the parent attribute of item_to_replace.
67+
6568 Parameters:
6669 item_to_replace (HedTag or HedGroup): The item to replace must exist or this will raise an error.
6770 new_contents (HedTag or HedGroup): Replacement contents.
6871
72+ :raises KeyError:
73+ - item_to_replace does not exist
74+
75+ :raises AttributeError:
76+ - item_to_replace has no parent set
77+ """
78+ parent = item_to_replace ._parent
79+ parent ._replace (item_to_replace = item_to_replace , new_contents = new_contents )
80+
81+ def _replace (self , item_to_replace , new_contents ):
82+ """ Replace an existing tag or group.
83+
84+ Parameters:
85+ item_to_replace (HedTag or HedGroup): The item to replace must exist and be a direct child,
86+ or this will raise an error.
87+ new_contents (HedTag or HedGroup): Replacement contents.
88+
6989 :raises KeyError:
7090 - item_to_replace does not exist
7191 """
7292 if self ._original_children is self .children :
7393 self ._original_children = self .children .copy ()
7494
75- replace_index = - 1
7695 for i , child in enumerate (self .children ):
7796 if item_to_replace is child :
78- replace_index = i
79- break
80- self .children [replace_index ] = new_contents
81- new_contents ._parent = self
97+ self .children [i ] = new_contents
98+ new_contents ._parent = self
99+ return
100+
101+ raise KeyError (f"The tag { item_to_replace } not found in the group." )
82102
83103 def remove (self , items_to_remove : Iterable [Union [HedTag , 'HedGroup' ]]):
84104 """ Remove any tags/groups in items_to_remove.
@@ -476,7 +496,7 @@ def find_def_tags(self, recursive=False, include_groups=3):
476496 for group in groups :
477497 def_tags += self ._get_def_tags_from_group (group )
478498 else :
479- def_tags = self ._get_def_tags_from_group (self )
499+ def_tags = self ._get_def_tags_from_group (self )
480500
481501 if include_groups == 0 or include_groups == 1 or include_groups == 2 :
482502 return [tag [include_groups ] for tag in def_tags ]
@@ -525,4 +545,4 @@ def find_tags_with_term(self, term, recursive=False, include_groups=2):
525545
526546 if include_groups == 0 or include_groups == 1 :
527547 return [tag [include_groups ] for tag in found_tags ]
528- return found_tags
548+ return found_tags
0 commit comments