diff --git a/Lib/shelve.py b/Lib/shelve.py index fd908bc23fe0ade..d71b243dd359e2e 100644 --- a/Lib/shelve.py +++ b/Lib/shelve.py @@ -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. @@ -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): diff --git a/Misc/NEWS.d/next/Library/2023-07-22-21-57-34.gh-issue-107089.Dnget2.rst b/Misc/NEWS.d/next/Library/2023-07-22-21-57-34.gh-issue-107089.Dnget2.rst index c67301a918ae600..9d5ba1a2d7ccba8 100644 --- a/Misc/NEWS.d/next/Library/2023-07-22-21-57-34.gh-issue-107089.Dnget2.rst +++ b/Misc/NEWS.d/next/Library/2023-07-22-21-57-34.gh-issue-107089.Dnget2.rst @@ -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. \ No newline at end of file