@@ -80,16 +80,30 @@ def _find_duplicate_keys(self, blocks: List[Block]) -> List[str]:
8080 seen_string_keys .add (block .key )
8181 return duplicate_keys
8282
83+ def _block_index (self , block : Block ) -> int :
84+ """Index of a block in the library, preferring identity over equality.
85+
86+ :param block: Block to look up.
87+ :raises ValueError: If block is not in library."""
88+ for i , b in enumerate (self ._blocks ):
89+ if b is block :
90+ return i
91+ # No identity match; fall back to equality (raises ValueError if not found).
92+ return self ._blocks .index (block )
93+
8394 def remove (self , blocks : Union [List [Block ], Block ]):
8495 """Remove blocks from library.
8596
97+ If equal duplicate blocks exist in the library, the exact (identical)
98+ instance is removed, if present; otherwise the first equal block.
99+
86100 :param blocks: Block or list of blocks to remove.
87101 :raises ValueError: If block is not in library."""
88102 if isinstance (blocks , Block ):
89103 blocks = [blocks ]
90104
91105 for block in blocks :
92- self ._blocks . remove (block )
106+ del self ._blocks [ self . _block_index (block )]
93107 if isinstance (block , Entry ):
94108 del self ._entries_by_key [block .key ]
95109 elif isinstance (block , String ):
@@ -98,14 +112,17 @@ def remove(self, blocks: Union[List[Block], Block]):
98112 def replace (self , old_block : Block , new_block : Block , fail_on_duplicate_key : bool = True ):
99113 """Replace a block with another block, at the same position.
100114
115+ If equal duplicate blocks exist in the library, the exact (identical)
116+ instance is replaced, if present; otherwise the first equal block.
117+
101118 :param old_block: Block to replace.
102119 :param new_block: Block to replace with.
103120 :param fail_on_duplicate_key: If False, adds a DuplicateKeyBlock if
104121 a block with new_block.key (other than old_block) already exists.
105122 :raises ValueError: If old_block is not in library or if fail_on_duplicate_key is True
106123 and a block with new_block.key (other than old_block) already exists."""
107124 try :
108- index = self ._blocks . index (old_block )
125+ index = self ._block_index (old_block )
109126 self .remove (old_block )
110127 except ValueError :
111128 raise ValueError ("Block to replace is not in library." )
0 commit comments