[Python-checkins] gh-85160: Reduce memory usage of `singledispatchmethod` (#107706)

AlexWaygood webhook-mailer at python.org
Mon Aug 7 08:46:40 EDT 2023


https://github.com/python/cpython/commit/2ac103c346ffe9d0e4c146402ce215c5ce6c1ef2
commit: 2ac103c346ffe9d0e4c146402ce215c5ce6c1ef2
branch: main
author: Alex Waygood <Alex.Waygood at Gmail.com>
committer: AlexWaygood <Alex.Waygood at Gmail.com>
date: 2023-08-07T13:46:36+01:00
summary:

gh-85160: Reduce memory usage of `singledispatchmethod` (#107706)

A small followup to #107148

Co-authored-by: Serhiy Storchaka <storchaka at gmail.com>

files:
M Lib/functools.py

diff --git a/Lib/functools.py b/Lib/functools.py
index 2a8a69b3c527a..be44ccdae6b69 100644
--- a/Lib/functools.py
+++ b/Lib/functools.py
@@ -928,14 +928,14 @@ class singledispatchmethod:
     """
 
     def __init__(self, func):
-        import weakref # see comment in singledispatch function
         if not callable(func) and not hasattr(func, "__get__"):
             raise TypeError(f"{func!r} is not callable or a descriptor")
 
         self.dispatcher = singledispatch(func)
         self.func = func
+
+        import weakref # see comment in singledispatch function
         self._method_cache = weakref.WeakKeyDictionary()
-        self._all_weakrefable_instances = True
 
     def register(self, cls, method=None):
         """generic_method.register(cls, func) -> func
@@ -945,11 +945,11 @@ def register(self, cls, method=None):
         return self.dispatcher.register(cls, func=method)
 
     def __get__(self, obj, cls=None):
-        if self._all_weakrefable_instances:
+        if self._method_cache is not None:
             try:
                 _method = self._method_cache[obj]
             except TypeError:
-                self._all_weakrefable_instances = False
+                self._method_cache = None
             except KeyError:
                 pass
             else:
@@ -963,7 +963,7 @@ def _method(*args, **kwargs):
         _method.register = self.register
         update_wrapper(_method, self.func)
 
-        if self._all_weakrefable_instances:
+        if self._method_cache is not None:
             self._method_cache[obj] = _method
 
         return _method



More information about the Python-checkins mailing list