8000 gh-85160: Reduce memory usage of `singledispatchmethod` (#107706) · python/cpython@2d731ef · GitHub
[go: up one dir, main page]

Skip to content

Commit 2d731ef

Browse files
AlexWaygoodserhiy-storchaka
authored andcommitted
gh-85160: Reduce memory usage of singledispatchmethod (#107706)
A small followup to #107148 Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
1 parent 2f8760c commit 2d731ef

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

Lib/functools.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -928,14 +928,14 @@ class singledispatchmethod:
928928
"""
929929

930930
def __init__(self, func):
931-
import weakref # see comment in singledispatch function
932931
if not callable(func) and not hasattr(func, "__get__"):
933932
raise TypeError(f"{func!r} is not callable or a descriptor")
934933

935934
self.dispatcher = singledispatch(func)
936935
self.func = func
936+
937+
import weakref # see comment in singledispatch function
937938
self._method_cache = weakref.WeakKeyDictionary()
938-
self._all_weakrefable_instances = True
939939

940940
def register(self, cls, method=None):
941941
"""generic_method.register(cls, func) -> func
@@ -945,11 +945,11 @@ def register(self, cls, method=None):
945945
return self.dispatcher.register(cls, func=method)
946946

947947
def __get__(self, obj, cls=None):
948-
if self._all_weakrefable_instances:
948+
if self._method_cache is not None:
949949
try:
950950
_method = self._method_cache[obj]
951951
except TypeError:
952-
self._all_weakrefable_instances = False
952+
self._method_cache = None
953953
except KeyError:
954954
pass
955955
else:
@@ -963,7 +963,7 @@ def _method(*args, **kwargs):
963963
_method.register = self.register
964964
update_wrapper(_method, self.func)
965965

966-
if self._all_weakrefable_instances:
966+
if self._method_cache is not None:
967967
self._method_cache[obj] = _method
968968

969969
return _method

0 commit comments

Comments
 (0)
0