@@ -1156,6 +1156,51 @@ def test():
11561156 # this test checks regular garbage collection
11571157 assert_python_ok ("-c" , code_inside_function )
11581158
1159+ def test_type_weakref_with_callback_should_be_none (self ):
1160+ # This test checks that weakrefs for types with callbacks
1161+ # are cleared before the finalizer is called
1162+ code = """
1163+ import weakref
1164+ def test():
1165+ class Class:
1166+ def __init__(self):
1167+ self._self = self
1168+ self._z = weakref.ref(Class, lambda x: None)
1169+
1170+ def __del__(self):
1171+ assert self._z() is None, "Type weakref is not None"
1172+
1173+ Class()
1174+
1175+ test()
1176+ """
1177+ _ , _ , stderr = assert_python_ok ("-c" , code )
1178+ assert b"Type weakref is not None" not in stderr
1179+
1180+ def test_type_weakref_without_callback_should_be_not_none (self ):
1181+ # This test checks that weakrefs for types without callbacks
1182+ # are cleared after the finalizer is called
1183+ code = """
1184+ import weakref
1185+ def test():
1186+ class Class:
1187+ def __init__(self):
1188+ self._self = self
1189+ self._x = weakref.ref(self)
1190+ self._z = weakref.ref(Class)
1191+
1192+ def __del__(self):
1193+ assert self._x() is None, "Instance weakref is not None"
1194+ assert self._z() is Class, "Type weakref is not Class"
1195+
1196+ Class()
1197+
1198+ test()
1199+ """
1200+ _ , _ , stderr = assert_python_ok ("-c" , code )
1201+ assert b"Instance weakref is not None" not in stderr
1202+ assert b"Type weakref is not Class" not in stderr
1203+
11591204
11601205class IncrementalGCTests (unittest .TestCase ):
11611206 @unittest .skipIf (_testinternalcapi is None , "requires _testinternalcapi" )
0 commit comments