Skip to content

Commit 345b714

Browse files
committed
gh-107089: call dbm.clear method
Because gh-107089 is peculiar to implementation details of dbm objects, it would be less disruptive to implement it in the DbfilenameShelf class, which is used for calls to shelve.open. Since it is known that the backing object is specifically one of the dbm objects, its clear method (see gh-107122) can be used with no fallback code.
1 parent 05ea943 commit 345b714

2 files changed

Lines changed: 9 additions & 22 deletions

File tree

Lib/shelve.py

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -171,26 +171,6 @@ 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-
193-
194174
class BsdDbShelf(Shelf):
195175
"""Shelf implementation using the "BSD" db interface.
196176
@@ -244,6 +224,13 @@ class DbfilenameShelf(Shelf):
244224
def __init__(self, filename, flag='c', protocol=None, writeback=False):
245225
import dbm
246226
Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
227+
228+
def clear(self):
229+
"""Remove all items from the shelf."""
230+
# Call through to the clear method on dbm-backed shelves.
231+
# see https://github.com/python/cpython/issues/107089
232+
self.cache.clear()
233+
self.dict.clear()
247234

248235

249236
def open(filename, flag='c', protocol=None, writeback=False):
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
The :meth:`Shelf.clear` method in the :mod:`shelve` module is much faster.
2-
Patch by James Cave.
1+
Shelves opened with :func:`shelve.open` have a much faster :meth:`clear`
2+
method. Patch by James Cave.

0 commit comments

Comments
 (0)