@@ -1027,9 +1027,7 @@ def __init__(self, func):
1027
1027
1028
1028
self .dispatcher = singledispatch (func )
1029
1029
self .func = func
1030
-
1031
- import weakref # see comment in singledispatch function
1032
- self ._method_cache = weakref .WeakKeyDictionary ()
1030
+ self ._method_cache = {}
1033
1031
1034
1032
def register (self , cls , method = None ):
1035
1033
"""generic_method.register(cls, func) -> func
@@ -1041,13 +1039,12 @@ def register(self, cls, method=None):
1041
1039
def __get__ (self , obj , cls = None ):
1042
1040
if self ._method_cache is not None :
1043
1041
try :
1044
- _method = self ._method_cache [obj ]
1045
- except TypeError :
1046
- self ._method_cache = None
1042
+ _obj_ref , _method = self ._method_cache [id (obj )]
1047
1043
except KeyError :
1048
1044
pass
1049
1045
else :
1050
- return _method
1046
+ if _obj_ref () is obj :
1047
+ return _method
1051
1048
1052
1049
dispatch = self .dispatcher .dispatch
1053
1050
funcname = getattr (self .func , '__name__' , 'singledispatchmethod method' )
@@ -1062,7 +1059,14 @@ def _method(*args, **kwargs):
1062
1059
update_wrapper (_method , self .func )
1063
1060
1064
1061
if self ._method_cache is not None :
1065
- self ._method_cache [obj ] = _method
1062
+ obj_id = id (obj )
1063
+
1064
+ def _remove (_ ):
1065
+ self ._method_cache .pop (obj_id , None )
1066
+
1067
+ import weakref # see comment in singledispatch function
1068
+ obj_ref = weakref .ref (obj , _remove )
1069
+ self ._method_cache [obj_id ] = (obj_ref , _method )
1066
1070
1067
1071
return _method
1068
1072
0 commit comments