Skip to content

Commit

Permalink
pythongh-107089: call dbm.clear method
Browse files Browse the repository at this point in the history
Because pythongh-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 pythongh-107122) can be used with no fallback code.
  • Loading branch information
jtcave committed Jul 24, 2023
1 parent f3e8a7b commit 726b3dc
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 22 deletions.
27 changes: 7 additions & 20 deletions Lib/shelve.py
Expand Up @@ -171,26 +171,6 @@ 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 Expand Up @@ -244,6 +224,13 @@ class DbfilenameShelf(Shelf):
def __init__(self, filename, flag='c', protocol=None, writeback=False):
import dbm
Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)

def clear(self):
"""Remove all items from the shelf."""
# Call through to the clear method on dbm-backed shelves.
# see https://github.com/python/cpython/issues/107089
self.cache.clear()
self.dict.clear()


def open(filename, flag='c', protocol=None, writeback=False):
Expand Down
@@ -1,2 +1,2 @@
The :meth:`Shelf.clear` method in the :mod:`shelve` module is much faster.
Patch by James Cave.
Shelves opened with :func:`shelve.open` have a much faster :meth:`clear`
method. Patch by James Cave.

0 comments on commit 726b3dc

Please sign in to comment.