Skip to content

Commit

Permalink
pythongh-107089: Improve Shelf.clear method performance
Browse files Browse the repository at this point in the history
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
  • Loading branch information
jtcave committed Jul 27, 2023
1 parent 8d61a71 commit 139dc7c
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
19 changes: 19 additions & 0 deletions Lib/shelve.py
Expand Up @@ -171,6 +171,25 @@ def sync(self):
if hasattr(self.dict, 'sync'):
self.dict.sync()

def clear(self):
"""Remove all items from the shelf."""
self.cache.clear()
try:
self.dict.clear()
except AttributeError:
# dbm objects don't have a clear method, so we need to do
# the clearing here.
keys = self.dict.keys()
if not isinstance(keys, list):
# The keys method on dbm objects returns a list.
# Typically, the keys method on a mapping returns a
# lazy iterator, so we need to watch out for that in
# case someone passes in a backing object that behaves
# that way.
keys = list(keys)
for k in keys:
del self.dict[k]


class BsdDbShelf(Shelf):
"""Shelf implementation using the "BSD" db interface.
Expand Down
1 change: 1 addition & 0 deletions Misc/ACKS
Expand Up @@ -289,6 +289,7 @@ Edward Catmur
Lorenzo M. Catucci
Bruno Cauet
Donn Cave
James Cave
Charles Cazabon
Jesús Cea Avión
Per Cederqvist
Expand Down
@@ -0,0 +1,2 @@
The :meth:`Shelf.clear` method in the :mod:`shelve` module is much faster.
Patch by James Cave.

0 comments on commit 139dc7c

Please sign in to comment.