Skip to content

Commit 6cbb066

Browse files
committed
pythongh-107089: Improve Shelf.clear method performance
The clear method used to be implemented by inheriting a mix-in from the MutableMapping ABC. It was a poor fit for shelves, and a better implementation is now in place
1 parent f8b7fe2 commit 6cbb066

3 files changed

Lines changed: 22 additions & 0 deletions

File tree

‎Lib/shelve.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,25 @@ def sync(self):
171171
if hasattr(self.dict, 'sync'):
172172
self.dict.sync()
173173

174+
def clear(self):
175+
"""Remove all items from the shelf."""
176+
self.cache.clear()
177+
try:
178+
self.dict.clear()
179+
except AttributeError:
180+
# dbm objects don't have a clear method, so we need to do
181+
# the clearing here.
182+
keys = self.dict.keys()
183+
if not isinstance(keys, list):
184+
# The keys method on dbm objects returns a list.
185+
# Typically, the keys method on a mapping returns a
186+
# lazy iterator, so we need to watch out for that in
187+
# case someone passes in a backing object that behaves
188+
# that way.
189+
keys = list(keys)
190+
for k in keys:
191+
del self.dict[k]
192+
174193

175194
class BsdDbShelf(Shelf):
176195
"""Shelf implementation using the "BSD" db interface.

‎Misc/ACKS‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,7 @@ Edward Catmur
289289
Lorenzo M. Catucci
290290
Bruno Cauet
291291
Donn Cave
292+
James Cave
292293
Charles Cazabon
293294
Jesús Cea Avión
294295
Per Cederqvist
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
The :meth:`Shelf.clear` method in the :mod:`shelve` module is much faster.
2+
Patch by James Cave.

0 commit comments

Comments
 (0)