Skip to content

Commit b78daea

Browse files
committed
fix: fix delete implementation.
1 parent 2d9f419 commit b78daea

File tree

2 files changed

+33
-9
lines changed

2 files changed

+33
-9
lines changed

src/lightning/pytorch/loggers/utilities.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ class _ListMap(list[_T]):
139139
140140
"""
141141

142-
def __init__(self, __iterable: Union[Iterable[_T], Mapping[str, _T]] = None):
142+
def __init__(self, __iterable: Union[Mapping[str, _T], Iterable[_T]] = None):
143143
if isinstance(__iterable, Mapping):
144144
# super inits list with values
145145
if any(not isinstance(x, str) for x in __iterable):
@@ -268,15 +268,18 @@ def __contains__(self, item: Union[_T, str]) -> bool:
268268

269269
def __delitem__(self, key: Union[int, slice, str]) -> None:
270270
if isinstance(key, (int, slice)):
271-
loggers = list.__getitem__(self, key)
272-
super(list, self).__delitem__(key)
273-
for logger in loggers if isinstance(key, slice) else [loggers]:
274-
name = getattr(logger, "name", None)
275-
if name:
276-
self._dict.pop(name, None)
271+
list.__delitem__(self, key)
272+
for _key in key.indices(len(self)) if isinstance(key, slice) else [key]:
273+
# update indices in the dict
274+
for str_key, idx in list(self._dict.items()):
275+
if idx == _key:
276+
self._dict.pop(str_key)
277+
elif idx > _key:
278+
self._dict[str_key] = idx - 1
277279
elif isinstance(key, str):
278-
logger = self._dict.pop(key)
279-
self.remove(logger)
280+
if key not in self._dict:
281+
raise KeyError(f"Key '{key}' not found.")
282+
self.__delitem__(self._dict[key])
280283
else:
281284
raise TypeError("Key must be int or str")
282285

tests/tests_pytorch/loggers/test_utilities.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,27 @@ def test_listmap_clear():
153153
assert len(lm.keys()) == 0
154154

155155

156+
def test_listmap_delitem():
157+
"""Test deleting items from the collection."""
158+
lm = _ListMap({"a": 1, "b": 2, "c": 3})
159+
lm.extend([3, 4, 5])
160+
del lm["b"]
161+
assert len(lm) == 5
162+
assert "b" not in lm
163+
del lm[0]
164+
assert len(lm) == 4
165+
assert "a" not in lm
166+
assert lm == [3, 3, 4, 5]
167+
168+
del lm[-1]
169+
assert len(lm) == 3
170+
assert lm == [3, 3, 4]
171+
172+
del lm[-2:]
173+
assert len(lm) == 1
174+
assert lm == [3]
175+
176+
156177
# Dict type properties tests
157178
def test_listmap_keys():
158179
lm = _ListMap({

0 commit comments

Comments
 (0)