From 139dc7cb594b9517b2735e1f66909bb41445e4e5 Mon Sep 17 00:00:00 2001 From: James Cave Date: Sat, 22 Jul 2023 21:58:09 -0400 Subject: [PATCH] gh-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 --- Lib/shelve.py | 19 +++++++++++++++++++ Misc/ACKS | 1 + ...-07-22-21-57-34.gh-issue-107089.Dnget2.rst | 2 ++ 3 files changed, 22 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2023-07-22-21-57-34.gh-issue-107089.Dnget2.rst diff --git a/Lib/shelve.py b/Lib/shelve.py index e053c397345a07e..fd908bc23fe0ade 100644 --- a/Lib/shelve.py +++ b/Lib/shelve.py @@ -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. diff --git a/Misc/ACKS b/Misc/ACKS index fadf488888aa8ba..8b8c5ad8434bd72 100644 --- a/Misc/ACKS +++ b/Misc/ACKS @@ -289,6 +289,7 @@ Edward Catmur Lorenzo M. Catucci Bruno Cauet Donn Cave +James Cave Charles Cazabon Jesús Cea Avión Per Cederqvist 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 new file mode 100644 index 000000000000000..c67301a918ae600 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-07-22-21-57-34.gh-issue-107089.Dnget2.rst @@ -0,0 +1,2 @@ +The :meth:`Shelf.clear` method in the :mod:`shelve` module is much faster. +Patch by James Cave.