blob: 85ab717c69fd187c712476dface907f3ed52825b [file] [log] [blame]
Fred Drakebc875f52004-02-04 23:14:14 +00001import gc
Fred Drake41deb1e2001-02-01 05:27:45 +00002import sys
Fred Drakeb0fefc52001-03-23 04:22:45 +00003import unittest
Raymond Hettinger53dbe392008-02-12 20:03:09 +00004import collections
Fred Drake41deb1e2001-02-01 05:27:45 +00005import weakref
Georg Brandlb533e262008-05-25 18:19:30 +00006import operator
Antoine Pitrouc1baa602010-01-08 17:54:23 +00007import contextlib
8import copy
Fred Drake41deb1e2001-02-01 05:27:45 +00009
Benjamin Petersonee8712c2008-05-20 21:35:26 +000010from test import support
Fred Drake41deb1e2001-02-01 05:27:45 +000011
Thomas Woutersb2137042007-02-01 18:02:27 +000012# Used in ReferencesTestCase.test_ref_created_during_del() .
13ref_from_del = None
Fred Drake41deb1e2001-02-01 05:27:45 +000014
15class C:
Fred Drakeb0fefc52001-03-23 04:22:45 +000016 def method(self):
17 pass
Fred Drake41deb1e2001-02-01 05:27:45 +000018
19
Fred Drakeb0fefc52001-03-23 04:22:45 +000020class Callable:
21 bar = None
Fred Drake41deb1e2001-02-01 05:27:45 +000022
Fred Drakeb0fefc52001-03-23 04:22:45 +000023 def __call__(self, x):
24 self.bar = x
Fred Drake41deb1e2001-02-01 05:27:45 +000025
26
Fred Drakeb0fefc52001-03-23 04:22:45 +000027def create_function():
28 def f(): pass
29 return f
30
31def create_bound_method():
32 return C().method
33
Fred Drake41deb1e2001-02-01 05:27:45 +000034
Antoine Pitroue11fecb2012-11-11 19:36:51 +010035class Object:
36 def __init__(self, arg):
37 self.arg = arg
38 def __repr__(self):
39 return "<Object %r>" % self.arg
40 def __eq__(self, other):
41 if isinstance(other, Object):
42 return self.arg == other.arg
43 return NotImplemented
44 def __lt__(self, other):
45 if isinstance(other, Object):
46 return self.arg < other.arg
47 return NotImplemented
48 def __hash__(self):
49 return hash(self.arg)
50
51class RefCycle:
52 def __init__(self):
53 self.cycle = self
54
55
Fred Drakeb0fefc52001-03-23 04:22:45 +000056class TestBase(unittest.TestCase):
57
58 def setUp(self):
59 self.cbcalled = 0
60
61 def callback(self, ref):
62 self.cbcalled += 1
Fred Drake41deb1e2001-02-01 05:27:45 +000063
64
Fred Drakeb0fefc52001-03-23 04:22:45 +000065class ReferencesTestCase(TestBase):
Fred Drake41deb1e2001-02-01 05:27:45 +000066
Fred Drakeb0fefc52001-03-23 04:22:45 +000067 def test_basic_ref(self):
68 self.check_basic_ref(C)
69 self.check_basic_ref(create_function)
70 self.check_basic_ref(create_bound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000071
Fred Drake43735da2002-04-11 03:59:42 +000072 # Just make sure the tp_repr handler doesn't raise an exception.
73 # Live reference:
74 o = C()
75 wr = weakref.ref(o)
Brett Cannon0b70cca2006-08-25 02:59:59 +000076 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000077 # Dead reference:
78 del o
Brett Cannon0b70cca2006-08-25 02:59:59 +000079 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000080
Fred Drakeb0fefc52001-03-23 04:22:45 +000081 def test_basic_callback(self):
82 self.check_basic_callback(C)
83 self.check_basic_callback(create_function)
84 self.check_basic_callback(create_bound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000085
Fred Drakeb0fefc52001-03-23 04:22:45 +000086 def test_multiple_callbacks(self):
87 o = C()
88 ref1 = weakref.ref(o, self.callback)
89 ref2 = weakref.ref(o, self.callback)
90 del o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +020091 self.assertIsNone(ref1(), "expected reference to be invalidated")
92 self.assertIsNone(ref2(), "expected reference to be invalidated")
93 self.assertEqual(self.cbcalled, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +000094 "callback not called the right number of times")
Fred Drake41deb1e2001-02-01 05:27:45 +000095
Fred Drake705088e2001-04-13 17:18:15 +000096 def test_multiple_selfref_callbacks(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +000097 # Make sure all references are invalidated before callbacks are called
Fred Drake705088e2001-04-13 17:18:15 +000098 #
99 # What's important here is that we're using the first
100 # reference in the callback invoked on the second reference
101 # (the most recently created ref is cleaned up first). This
102 # tests that all references to the object are invalidated
103 # before any of the callbacks are invoked, so that we only
104 # have one invocation of _weakref.c:cleanup_helper() active
105 # for a particular object at a time.
106 #
107 def callback(object, self=self):
108 self.ref()
109 c = C()
110 self.ref = weakref.ref(c, callback)
111 ref1 = weakref.ref(c, callback)
112 del c
113
Fred Drakeb0fefc52001-03-23 04:22:45 +0000114 def test_proxy_ref(self):
115 o = C()
116 o.bar = 1
117 ref1 = weakref.proxy(o, self.callback)
118 ref2 = weakref.proxy(o, self.callback)
119 del o
Fred Drake41deb1e2001-02-01 05:27:45 +0000120
Fred Drakeb0fefc52001-03-23 04:22:45 +0000121 def check(proxy):
122 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000123
Neal Norwitz2633c692007-02-26 22:22:47 +0000124 self.assertRaises(ReferenceError, check, ref1)
125 self.assertRaises(ReferenceError, check, ref2)
126 self.assertRaises(ReferenceError, bool, weakref.proxy(C()))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000127 self.assertEqual(self.cbcalled, 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000128
Fred Drakeb0fefc52001-03-23 04:22:45 +0000129 def check_basic_ref(self, factory):
130 o = factory()
131 ref = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200132 self.assertIsNotNone(ref(),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000133 "weak reference to live object should be live")
134 o2 = ref()
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200135 self.assertIs(o, o2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000136 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000137
Fred Drakeb0fefc52001-03-23 04:22:45 +0000138 def check_basic_callback(self, factory):
139 self.cbcalled = 0
140 o = factory()
141 ref = weakref.ref(o, self.callback)
142 del o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200143 self.assertEqual(self.cbcalled, 1,
Fred Drake705088e2001-04-13 17:18:15 +0000144 "callback did not properly set 'cbcalled'")
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200145 self.assertIsNone(ref(),
Fred Drake705088e2001-04-13 17:18:15 +0000146 "ref2 should be dead after deleting object reference")
Fred Drake41deb1e2001-02-01 05:27:45 +0000147
Fred Drakeb0fefc52001-03-23 04:22:45 +0000148 def test_ref_reuse(self):
149 o = C()
150 ref1 = weakref.ref(o)
151 # create a proxy to make sure that there's an intervening creation
152 # between these two; it should make no difference
153 proxy = weakref.proxy(o)
154 ref2 = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200155 self.assertIs(ref1, ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000156 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000157
Fred Drakeb0fefc52001-03-23 04:22:45 +0000158 o = C()
159 proxy = weakref.proxy(o)
160 ref1 = weakref.ref(o)
161 ref2 = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200162 self.assertIs(ref1, ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000163 "reference object w/out callback should be re-used")
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200164 self.assertEqual(weakref.getweakrefcount(o), 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000165 "wrong weak ref count for object")
166 del proxy
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200167 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000168 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000169
Fred Drakeb0fefc52001-03-23 04:22:45 +0000170 def test_proxy_reuse(self):
171 o = C()
172 proxy1 = weakref.proxy(o)
173 ref = weakref.ref(o)
174 proxy2 = weakref.proxy(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200175 self.assertIs(proxy1, proxy2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000176 "proxy object w/out callback should have been re-used")
177
178 def test_basic_proxy(self):
179 o = C()
180 self.check_proxy(o, weakref.proxy(o))
181
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000182 L = collections.UserList()
Fred Drake5935ff02001-12-19 16:54:23 +0000183 p = weakref.proxy(L)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000184 self.assertFalse(p, "proxy for empty UserList should be false")
Fred Drake5935ff02001-12-19 16:54:23 +0000185 p.append(12)
186 self.assertEqual(len(L), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000187 self.assertTrue(p, "proxy for non-empty UserList should be true")
Fred Drake5935ff02001-12-19 16:54:23 +0000188 p[:] = [2, 3]
189 self.assertEqual(len(L), 2)
190 self.assertEqual(len(p), 2)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000191 self.assertIn(3, p, "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000192 p[1] = 5
193 self.assertEqual(L[1], 5)
194 self.assertEqual(p[1], 5)
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000195 L2 = collections.UserList(L)
Fred Drake5935ff02001-12-19 16:54:23 +0000196 p2 = weakref.proxy(L2)
197 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000198 ## self.assertEqual(repr(L2), repr(p2))
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000199 L3 = collections.UserList(range(10))
Fred Drake43735da2002-04-11 03:59:42 +0000200 p3 = weakref.proxy(L3)
201 self.assertEqual(L3[:], p3[:])
202 self.assertEqual(L3[5:], p3[5:])
203 self.assertEqual(L3[:5], p3[:5])
204 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000205
Benjamin Peterson32019772009-11-19 03:08:32 +0000206 def test_proxy_unicode(self):
207 # See bug 5037
208 class C(object):
209 def __str__(self):
210 return "string"
211 def __bytes__(self):
212 return b"bytes"
213 instance = C()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000214 self.assertIn("__bytes__", dir(weakref.proxy(instance)))
Benjamin Peterson32019772009-11-19 03:08:32 +0000215 self.assertEqual(bytes(weakref.proxy(instance)), b"bytes")
216
Georg Brandlb533e262008-05-25 18:19:30 +0000217 def test_proxy_index(self):
218 class C:
219 def __index__(self):
220 return 10
221 o = C()
222 p = weakref.proxy(o)
223 self.assertEqual(operator.index(p), 10)
224
225 def test_proxy_div(self):
226 class C:
227 def __floordiv__(self, other):
228 return 42
229 def __ifloordiv__(self, other):
230 return 21
231 o = C()
232 p = weakref.proxy(o)
233 self.assertEqual(p // 5, 42)
234 p //= 5
235 self.assertEqual(p, 21)
236
Fred Drakeea2adc92004-02-03 19:56:46 +0000237 # The PyWeakref_* C API is documented as allowing either NULL or
238 # None as the value for the callback, where either means "no
239 # callback". The "no callback" ref and proxy objects are supposed
240 # to be shared so long as they exist by all callers so long as
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000241 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000242 # was not honored, and was broken in different ways for
243 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
244
245 def test_shared_ref_without_callback(self):
246 self.check_shared_without_callback(weakref.ref)
247
248 def test_shared_proxy_without_callback(self):
249 self.check_shared_without_callback(weakref.proxy)
250
251 def check_shared_without_callback(self, makeref):
252 o = Object(1)
253 p1 = makeref(o, None)
254 p2 = makeref(o, None)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200255 self.assertIs(p1, p2, "both callbacks were None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000256 del p1, p2
257 p1 = makeref(o)
258 p2 = makeref(o, None)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200259 self.assertIs(p1, p2, "callbacks were NULL, None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000260 del p1, p2
261 p1 = makeref(o)
262 p2 = makeref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200263 self.assertIs(p1, p2, "both callbacks were NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000264 del p1, p2
265 p1 = makeref(o, None)
266 p2 = makeref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200267 self.assertIs(p1, p2, "callbacks were None, NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000268
Fred Drakeb0fefc52001-03-23 04:22:45 +0000269 def test_callable_proxy(self):
270 o = Callable()
271 ref1 = weakref.proxy(o)
272
273 self.check_proxy(o, ref1)
274
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200275 self.assertIs(type(ref1), weakref.CallableProxyType,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000276 "proxy is not of callable type")
277 ref1('twinkies!')
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200278 self.assertEqual(o.bar, 'twinkies!',
Fred Drakeb0fefc52001-03-23 04:22:45 +0000279 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000280 ref1(x='Splat.')
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200281 self.assertEqual(o.bar, 'Splat.',
Fred Drake3bb4d212001-10-18 19:28:29 +0000282 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000283
284 # expect due to too few args
285 self.assertRaises(TypeError, ref1)
286
287 # expect due to too many args
288 self.assertRaises(TypeError, ref1, 1, 2, 3)
289
290 def check_proxy(self, o, proxy):
291 o.foo = 1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200292 self.assertEqual(proxy.foo, 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000293 "proxy does not reflect attribute addition")
294 o.foo = 2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200295 self.assertEqual(proxy.foo, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000296 "proxy does not reflect attribute modification")
297 del o.foo
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200298 self.assertFalse(hasattr(proxy, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000299 "proxy does not reflect attribute removal")
300
301 proxy.foo = 1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200302 self.assertEqual(o.foo, 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000303 "object does not reflect attribute addition via proxy")
304 proxy.foo = 2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200305 self.assertEqual(o.foo, 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000306 "object does not reflect attribute modification via proxy")
307 del proxy.foo
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200308 self.assertFalse(hasattr(o, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000309 "object does not reflect attribute removal via proxy")
310
Raymond Hettingerd693a812003-06-30 04:18:48 +0000311 def test_proxy_deletion(self):
312 # Test clearing of SF bug #762891
313 class Foo:
314 result = None
315 def __delitem__(self, accessor):
316 self.result = accessor
317 g = Foo()
318 f = weakref.proxy(g)
319 del f[0]
320 self.assertEqual(f.result, 0)
321
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000322 def test_proxy_bool(self):
323 # Test clearing of SF bug #1170766
324 class List(list): pass
325 lyst = List()
326 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
327
Fred Drakeb0fefc52001-03-23 04:22:45 +0000328 def test_getweakrefcount(self):
329 o = C()
330 ref1 = weakref.ref(o)
331 ref2 = weakref.ref(o, self.callback)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200332 self.assertEqual(weakref.getweakrefcount(o), 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000333 "got wrong number of weak reference objects")
334
335 proxy1 = weakref.proxy(o)
336 proxy2 = weakref.proxy(o, self.callback)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200337 self.assertEqual(weakref.getweakrefcount(o), 4,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000338 "got wrong number of weak reference objects")
339
Fred Drakeea2adc92004-02-03 19:56:46 +0000340 del ref1, ref2, proxy1, proxy2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200341 self.assertEqual(weakref.getweakrefcount(o), 0,
Fred Drakeea2adc92004-02-03 19:56:46 +0000342 "weak reference objects not unlinked from"
343 " referent when discarded.")
344
Walter Dörwaldb167b042003-12-11 12:34:05 +0000345 # assumes ints do not support weakrefs
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200346 self.assertEqual(weakref.getweakrefcount(1), 0,
Walter Dörwaldb167b042003-12-11 12:34:05 +0000347 "got wrong number of weak reference objects for int")
348
Fred Drakeb0fefc52001-03-23 04:22:45 +0000349 def test_getweakrefs(self):
350 o = C()
351 ref1 = weakref.ref(o, self.callback)
352 ref2 = weakref.ref(o, self.callback)
353 del ref1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200354 self.assertEqual(weakref.getweakrefs(o), [ref2],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000355 "list of refs does not match")
356
357 o = C()
358 ref1 = weakref.ref(o, self.callback)
359 ref2 = weakref.ref(o, self.callback)
360 del ref2
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200361 self.assertEqual(weakref.getweakrefs(o), [ref1],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000362 "list of refs does not match")
363
Fred Drakeea2adc92004-02-03 19:56:46 +0000364 del ref1
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200365 self.assertEqual(weakref.getweakrefs(o), [],
Fred Drakeea2adc92004-02-03 19:56:46 +0000366 "list of refs not cleared")
367
Walter Dörwaldb167b042003-12-11 12:34:05 +0000368 # assumes ints do not support weakrefs
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200369 self.assertEqual(weakref.getweakrefs(1), [],
Walter Dörwaldb167b042003-12-11 12:34:05 +0000370 "list of refs does not match for int")
371
Fred Drake39c27f12001-10-18 18:06:05 +0000372 def test_newstyle_number_ops(self):
373 class F(float):
374 pass
375 f = F(2.0)
376 p = weakref.proxy(f)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200377 self.assertEqual(p + 1.0, 3.0)
378 self.assertEqual(1.0 + p, 3.0) # this used to SEGV
Fred Drake39c27f12001-10-18 18:06:05 +0000379
Fred Drake2a64f462001-12-10 23:46:02 +0000380 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000381 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000382 # Regression test for SF bug #478534.
383 class BogusError(Exception):
384 pass
385 data = {}
386 def remove(k):
387 del data[k]
388 def encapsulate():
389 f = lambda : ()
390 data[weakref.ref(f, remove)] = None
391 raise BogusError
392 try:
393 encapsulate()
394 except BogusError:
395 pass
396 else:
397 self.fail("exception not properly restored")
398 try:
399 encapsulate()
400 except BogusError:
401 pass
402 else:
403 self.fail("exception not properly restored")
404
Tim Petersadd09b42003-11-12 20:43:28 +0000405 def test_sf_bug_840829(self):
406 # "weakref callbacks and gc corrupt memory"
407 # subtype_dealloc erroneously exposed a new-style instance
408 # already in the process of getting deallocated to gc,
409 # causing double-deallocation if the instance had a weakref
410 # callback that triggered gc.
411 # If the bug exists, there probably won't be an obvious symptom
412 # in a release build. In a debug build, a segfault will occur
413 # when the second attempt to remove the instance from the "list
414 # of all objects" occurs.
415
416 import gc
417
418 class C(object):
419 pass
420
421 c = C()
422 wr = weakref.ref(c, lambda ignore: gc.collect())
423 del c
424
Tim Petersf7f9e992003-11-13 21:59:32 +0000425 # There endeth the first part. It gets worse.
426 del wr
427
428 c1 = C()
429 c1.i = C()
430 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
431
432 c2 = C()
433 c2.c1 = c1
434 del c1 # still alive because c2 points to it
435
436 # Now when subtype_dealloc gets called on c2, it's not enough just
437 # that c2 is immune from gc while the weakref callbacks associated
438 # with c2 execute (there are none in this 2nd half of the test, btw).
439 # subtype_dealloc goes on to call the base classes' deallocs too,
440 # so any gc triggered by weakref callbacks associated with anything
441 # torn down by a base class dealloc can also trigger double
442 # deallocation of c2.
443 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000444
Tim Peters403a2032003-11-20 21:21:46 +0000445 def test_callback_in_cycle_1(self):
446 import gc
447
448 class J(object):
449 pass
450
451 class II(object):
452 def acallback(self, ignore):
453 self.J
454
455 I = II()
456 I.J = J
457 I.wr = weakref.ref(J, I.acallback)
458
459 # Now J and II are each in a self-cycle (as all new-style class
460 # objects are, since their __mro__ points back to them). I holds
461 # both a weak reference (I.wr) and a strong reference (I.J) to class
462 # J. I is also in a cycle (I.wr points to a weakref that references
463 # I.acallback). When we del these three, they all become trash, but
464 # the cycles prevent any of them from getting cleaned up immediately.
465 # Instead they have to wait for cyclic gc to deduce that they're
466 # trash.
467 #
468 # gc used to call tp_clear on all of them, and the order in which
469 # it does that is pretty accidental. The exact order in which we
470 # built up these things manages to provoke gc into running tp_clear
471 # in just the right order (I last). Calling tp_clear on II leaves
472 # behind an insane class object (its __mro__ becomes NULL). Calling
473 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
474 # just then because of the strong reference from I.J. Calling
475 # tp_clear on I starts to clear I's __dict__, and just happens to
476 # clear I.J first -- I.wr is still intact. That removes the last
477 # reference to J, which triggers the weakref callback. The callback
478 # tries to do "self.J", and instances of new-style classes look up
479 # attributes ("J") in the class dict first. The class (II) wants to
480 # search II.__mro__, but that's NULL. The result was a segfault in
481 # a release build, and an assert failure in a debug build.
482 del I, J, II
483 gc.collect()
484
485 def test_callback_in_cycle_2(self):
486 import gc
487
488 # This is just like test_callback_in_cycle_1, except that II is an
489 # old-style class. The symptom is different then: an instance of an
490 # old-style class looks in its own __dict__ first. 'J' happens to
491 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
492 # __dict__, so the attribute isn't found. The difference is that
493 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
494 # __mro__), so no segfault occurs. Instead it got:
495 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
496 # Exception exceptions.AttributeError:
497 # "II instance has no attribute 'J'" in <bound method II.acallback
498 # of <?.II instance at 0x00B9B4B8>> ignored
499
500 class J(object):
501 pass
502
503 class II:
504 def acallback(self, ignore):
505 self.J
506
507 I = II()
508 I.J = J
509 I.wr = weakref.ref(J, I.acallback)
510
511 del I, J, II
512 gc.collect()
513
514 def test_callback_in_cycle_3(self):
515 import gc
516
517 # This one broke the first patch that fixed the last two. In this
518 # case, the objects reachable from the callback aren't also reachable
519 # from the object (c1) *triggering* the callback: you can get to
520 # c1 from c2, but not vice-versa. The result was that c2's __dict__
521 # got tp_clear'ed by the time the c2.cb callback got invoked.
522
523 class C:
524 def cb(self, ignore):
525 self.me
526 self.c1
527 self.wr
528
529 c1, c2 = C(), C()
530
531 c2.me = c2
532 c2.c1 = c1
533 c2.wr = weakref.ref(c1, c2.cb)
534
535 del c1, c2
536 gc.collect()
537
538 def test_callback_in_cycle_4(self):
539 import gc
540
541 # Like test_callback_in_cycle_3, except c2 and c1 have different
542 # classes. c2's class (C) isn't reachable from c1 then, so protecting
543 # objects reachable from the dying object (c1) isn't enough to stop
544 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
545 # The result was a segfault (C.__mro__ was NULL when the callback
546 # tried to look up self.me).
547
548 class C(object):
549 def cb(self, ignore):
550 self.me
551 self.c1
552 self.wr
553
554 class D:
555 pass
556
557 c1, c2 = D(), C()
558
559 c2.me = c2
560 c2.c1 = c1
561 c2.wr = weakref.ref(c1, c2.cb)
562
563 del c1, c2, C, D
564 gc.collect()
565
566 def test_callback_in_cycle_resurrection(self):
567 import gc
568
569 # Do something nasty in a weakref callback: resurrect objects
570 # from dead cycles. For this to be attempted, the weakref and
571 # its callback must also be part of the cyclic trash (else the
572 # objects reachable via the callback couldn't be in cyclic trash
573 # to begin with -- the callback would act like an external root).
574 # But gc clears trash weakrefs with callbacks early now, which
575 # disables the callbacks, so the callbacks shouldn't get called
576 # at all (and so nothing actually gets resurrected).
577
578 alist = []
579 class C(object):
580 def __init__(self, value):
581 self.attribute = value
582
583 def acallback(self, ignore):
584 alist.append(self.c)
585
586 c1, c2 = C(1), C(2)
587 c1.c = c2
588 c2.c = c1
589 c1.wr = weakref.ref(c2, c1.acallback)
590 c2.wr = weakref.ref(c1, c2.acallback)
591
592 def C_went_away(ignore):
593 alist.append("C went away")
594 wr = weakref.ref(C, C_went_away)
595
596 del c1, c2, C # make them all trash
597 self.assertEqual(alist, []) # del isn't enough to reclaim anything
598
599 gc.collect()
600 # c1.wr and c2.wr were part of the cyclic trash, so should have
601 # been cleared without their callbacks executing. OTOH, the weakref
602 # to C is bound to a function local (wr), and wasn't trash, so that
603 # callback should have been invoked when C went away.
604 self.assertEqual(alist, ["C went away"])
605 # The remaining weakref should be dead now (its callback ran).
606 self.assertEqual(wr(), None)
607
608 del alist[:]
609 gc.collect()
610 self.assertEqual(alist, [])
611
612 def test_callbacks_on_callback(self):
613 import gc
614
615 # Set up weakref callbacks *on* weakref callbacks.
616 alist = []
617 def safe_callback(ignore):
618 alist.append("safe_callback called")
619
620 class C(object):
621 def cb(self, ignore):
622 alist.append("cb called")
623
624 c, d = C(), C()
625 c.other = d
626 d.other = c
627 callback = c.cb
628 c.wr = weakref.ref(d, callback) # this won't trigger
629 d.wr = weakref.ref(callback, d.cb) # ditto
630 external_wr = weakref.ref(callback, safe_callback) # but this will
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200631 self.assertIs(external_wr(), callback)
Tim Peters403a2032003-11-20 21:21:46 +0000632
633 # The weakrefs attached to c and d should get cleared, so that
634 # C.cb is never called. But external_wr isn't part of the cyclic
635 # trash, and no cyclic trash is reachable from it, so safe_callback
636 # should get invoked when the bound method object callback (c.cb)
637 # -- which is itself a callback, and also part of the cyclic trash --
638 # gets reclaimed at the end of gc.
639
640 del callback, c, d, C
641 self.assertEqual(alist, []) # del isn't enough to clean up cycles
642 gc.collect()
643 self.assertEqual(alist, ["safe_callback called"])
644 self.assertEqual(external_wr(), None)
645
646 del alist[:]
647 gc.collect()
648 self.assertEqual(alist, [])
649
Fred Drakebc875f52004-02-04 23:14:14 +0000650 def test_gc_during_ref_creation(self):
651 self.check_gc_during_creation(weakref.ref)
652
653 def test_gc_during_proxy_creation(self):
654 self.check_gc_during_creation(weakref.proxy)
655
656 def check_gc_during_creation(self, makeref):
657 thresholds = gc.get_threshold()
658 gc.set_threshold(1, 1, 1)
659 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000660 class A:
661 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000662
663 def callback(*args):
664 pass
665
Fred Drake55cf4342004-02-13 19:21:57 +0000666 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000667
Fred Drake55cf4342004-02-13 19:21:57 +0000668 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000669 a.a = a
670 a.wr = makeref(referenced)
671
672 try:
673 # now make sure the object and the ref get labeled as
674 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000675 a = A()
676 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000677
678 finally:
679 gc.set_threshold(*thresholds)
680
Thomas Woutersb2137042007-02-01 18:02:27 +0000681 def test_ref_created_during_del(self):
682 # Bug #1377858
683 # A weakref created in an object's __del__() would crash the
684 # interpreter when the weakref was cleaned up since it would refer to
685 # non-existent memory. This test should not segfault the interpreter.
686 class Target(object):
687 def __del__(self):
688 global ref_from_del
689 ref_from_del = weakref.ref(self)
690
691 w = Target()
692
Benjamin Peterson9aa42992008-09-10 21:57:34 +0000693 def test_init(self):
694 # Issue 3634
695 # <weakref to class>.__init__() doesn't check errors correctly
696 r = weakref.ref(Exception)
697 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
698 # No exception should be raised here
699 gc.collect()
700
Antoine Pitrou3af01a12010-03-31 21:40:47 +0000701 def test_classes(self):
702 # Check that classes are weakrefable.
703 class A(object):
704 pass
705 l = []
706 weakref.ref(int)
707 a = weakref.ref(A, l.append)
708 A = None
709 gc.collect()
710 self.assertEqual(a(), None)
711 self.assertEqual(l, [a])
712
Antoine Pitroue11fecb2012-11-11 19:36:51 +0100713 def test_equality(self):
714 # Alive weakrefs defer equality testing to their underlying object.
715 x = Object(1)
716 y = Object(1)
717 z = Object(2)
718 a = weakref.ref(x)
719 b = weakref.ref(y)
720 c = weakref.ref(z)
721 d = weakref.ref(x)
722 # Note how we directly test the operators here, to stress both
723 # __eq__ and __ne__.
724 self.assertTrue(a == b)
725 self.assertFalse(a != b)
726 self.assertFalse(a == c)
727 self.assertTrue(a != c)
728 self.assertTrue(a == d)
729 self.assertFalse(a != d)
730 del x, y, z
731 gc.collect()
732 for r in a, b, c:
733 # Sanity check
734 self.assertIs(r(), None)
735 # Dead weakrefs compare by identity: whether `a` and `d` are the
736 # same weakref object is an implementation detail, since they pointed
737 # to the same original object and didn't have a callback.
738 # (see issue #16453).
739 self.assertFalse(a == b)
740 self.assertTrue(a != b)
741 self.assertFalse(a == c)
742 self.assertTrue(a != c)
743 self.assertEqual(a == d, a is d)
744 self.assertEqual(a != d, a is not d)
745
746 def test_ordering(self):
747 # weakrefs cannot be ordered, even if the underlying objects can.
748 ops = [operator.lt, operator.gt, operator.le, operator.ge]
749 x = Object(1)
750 y = Object(1)
751 a = weakref.ref(x)
752 b = weakref.ref(y)
753 for op in ops:
754 self.assertRaises(TypeError, op, a, b)
755 # Same when dead.
756 del x, y
757 gc.collect()
758 for op in ops:
759 self.assertRaises(TypeError, op, a, b)
760
761 def test_hashing(self):
762 # Alive weakrefs hash the same as the underlying object
763 x = Object(42)
764 y = Object(42)
765 a = weakref.ref(x)
766 b = weakref.ref(y)
767 self.assertEqual(hash(a), hash(42))
768 del x, y
769 gc.collect()
770 # Dead weakrefs:
771 # - retain their hash is they were hashed when alive;
772 # - otherwise, cannot be hashed.
773 self.assertEqual(hash(a), hash(42))
774 self.assertRaises(TypeError, hash, b)
775
Antoine Pitrou62a0d6e2012-12-08 21:15:26 +0100776 def test_trashcan_16602(self):
777 # Issue #16602: when a weakref's target was part of a long
778 # deallocation chain, the trashcan mechanism could delay clearing
779 # of the weakref and make the target object visible from outside
780 # code even though its refcount had dropped to 0. A crash ensued.
781 class C:
782 def __init__(self, parent):
783 if not parent:
784 return
785 wself = weakref.ref(self)
786 def cb(wparent):
787 o = wself()
788 self.wparent = weakref.ref(parent, cb)
789
790 d = weakref.WeakKeyDictionary()
791 root = c = C(None)
792 for n in range(100):
793 d[c] = c = C(c)
794 del root
795 gc.collect()
796
Fred Drake0a4dd392004-07-02 18:57:45 +0000797
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000798class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000799
800 def test_subclass_refs(self):
801 class MyRef(weakref.ref):
802 def __init__(self, ob, callback=None, value=42):
803 self.value = value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000804 super().__init__(ob, callback)
Fred Drake0a4dd392004-07-02 18:57:45 +0000805 def __call__(self):
806 self.called = True
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000807 return super().__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000808 o = Object("foo")
809 mr = MyRef(o, value=24)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200810 self.assertIs(mr(), o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000811 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000812 self.assertEqual(mr.value, 24)
813 del o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200814 self.assertIsNone(mr())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000815 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000816
817 def test_subclass_refs_dont_replace_standard_refs(self):
818 class MyRef(weakref.ref):
819 pass
820 o = Object(42)
821 r1 = MyRef(o)
822 r2 = weakref.ref(o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200823 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000824 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
825 self.assertEqual(weakref.getweakrefcount(o), 2)
826 r3 = MyRef(o)
827 self.assertEqual(weakref.getweakrefcount(o), 3)
828 refs = weakref.getweakrefs(o)
829 self.assertEqual(len(refs), 3)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200830 self.assertIs(r2, refs[0])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000831 self.assertIn(r1, refs[1:])
832 self.assertIn(r3, refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +0000833
834 def test_subclass_refs_dont_conflate_callbacks(self):
835 class MyRef(weakref.ref):
836 pass
837 o = Object(42)
838 r1 = MyRef(o, id)
839 r2 = MyRef(o, str)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200840 self.assertIsNot(r1, r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000841 refs = weakref.getweakrefs(o)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000842 self.assertIn(r1, refs)
843 self.assertIn(r2, refs)
Fred Drake0a4dd392004-07-02 18:57:45 +0000844
845 def test_subclass_refs_with_slots(self):
846 class MyRef(weakref.ref):
847 __slots__ = "slot1", "slot2"
848 def __new__(type, ob, callback, slot1, slot2):
849 return weakref.ref.__new__(type, ob, callback)
850 def __init__(self, ob, callback, slot1, slot2):
851 self.slot1 = slot1
852 self.slot2 = slot2
853 def meth(self):
854 return self.slot1 + self.slot2
855 o = Object(42)
856 r = MyRef(o, None, "abc", "def")
857 self.assertEqual(r.slot1, "abc")
858 self.assertEqual(r.slot2, "def")
859 self.assertEqual(r.meth(), "abcdef")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000860 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +0000861
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000862 def test_subclass_refs_with_cycle(self):
863 # Bug #3110
864 # An instance of a weakref subclass can have attributes.
865 # If such a weakref holds the only strong reference to the object,
866 # deleting the weakref will delete the object. In this case,
867 # the callback must not be called, because the ref object is
868 # being deleted.
869 class MyRef(weakref.ref):
870 pass
871
872 # Use a local callback, for "regrtest -R::"
873 # to detect refcounting problems
874 def callback(w):
875 self.cbcalled += 1
876
877 o = C()
878 r1 = MyRef(o, callback)
879 r1.o = o
880 del o
881
882 del r1 # Used to crash here
883
884 self.assertEqual(self.cbcalled, 0)
885
886 # Same test, with two weakrefs to the same object
887 # (since code paths are different)
888 o = C()
889 r1 = MyRef(o, callback)
890 r2 = MyRef(o, callback)
891 r1.r = r2
892 r2.o = o
893 del o
894 del r2
895
896 del r1 # Used to crash here
897
898 self.assertEqual(self.cbcalled, 0)
899
Fred Drake0a4dd392004-07-02 18:57:45 +0000900
Fred Drakeb0fefc52001-03-23 04:22:45 +0000901class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000902
Fred Drakeb0fefc52001-03-23 04:22:45 +0000903 COUNT = 10
904
Antoine Pitroubbe2f602012-03-01 16:26:35 +0100905 def check_len_cycles(self, dict_type, cons):
906 N = 20
907 items = [RefCycle() for i in range(N)]
908 dct = dict_type(cons(o) for o in items)
909 # Keep an iterator alive
910 it = dct.items()
911 try:
912 next(it)
913 except StopIteration:
914 pass
915 del items
916 gc.collect()
917 n1 = len(dct)
918 del it
919 gc.collect()
920 n2 = len(dct)
921 # one item may be kept alive inside the iterator
922 self.assertIn(n1, (0, 1))
923 self.assertEqual(n2, 0)
924
925 def test_weak_keyed_len_cycles(self):
926 self.check_len_cycles(weakref.WeakKeyDictionary, lambda k: (k, 1))
927
928 def test_weak_valued_len_cycles(self):
929 self.check_len_cycles(weakref.WeakValueDictionary, lambda k: (1, k))
930
931 def check_len_race(self, dict_type, cons):
932 # Extended sanity checks for len() in the face of cyclic collection
933 self.addCleanup(gc.set_threshold, *gc.get_threshold())
934 for th in range(1, 100):
935 N = 20
936 gc.collect(0)
937 gc.set_threshold(th, th, th)
938 items = [RefCycle() for i in range(N)]
939 dct = dict_type(cons(o) for o in items)
940 del items
941 # All items will be collected at next garbage collection pass
942 it = dct.items()
943 try:
944 next(it)
945 except StopIteration:
946 pass
947 n1 = len(dct)
948 del it
949 n2 = len(dct)
950 self.assertGreaterEqual(n1, 0)
951 self.assertLessEqual(n1, N)
952 self.assertGreaterEqual(n2, 0)
953 self.assertLessEqual(n2, n1)
954
955 def test_weak_keyed_len_race(self):
956 self.check_len_race(weakref.WeakKeyDictionary, lambda k: (k, 1))
957
958 def test_weak_valued_len_race(self):
959 self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k))
960
Fred Drakeb0fefc52001-03-23 04:22:45 +0000961 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000962 #
963 # This exercises d.copy(), d.items(), d[], del d[], len(d).
964 #
965 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000966 for o in objects:
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000967 self.assertEqual(weakref.getweakrefcount(o), 1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200968 self.assertIs(o, dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000969 "wrong object returned by weak dict!")
Barry Warsawecaab832008-09-04 01:42:51 +0000970 items1 = list(dict.items())
971 items2 = list(dict.copy().items())
Fred Drakeb0fefc52001-03-23 04:22:45 +0000972 items1.sort()
973 items2.sort()
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000974 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000975 "cloning of weak-valued dictionary did not work!")
976 del items1, items2
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000977 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000978 del objects[0]
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000979 self.assertEqual(len(dict), self.COUNT - 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000980 "deleting object did not cause dictionary update")
981 del objects, o
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000982 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000983 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000984 # regression on SF bug #447152:
985 dict = weakref.WeakValueDictionary()
986 self.assertRaises(KeyError, dict.__getitem__, 1)
987 dict[2] = C()
988 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000989
990 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000991 #
992 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000993 # len(d), k in d.
Fred Drake0e540c32001-05-02 05:44:22 +0000994 #
995 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000996 for o in objects:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200997 self.assertEqual(weakref.getweakrefcount(o), 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000998 "wrong number of weak references to %r!" % o)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +0200999 self.assertIs(o.arg, dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001000 "wrong object returned by weak dict!")
1001 items1 = dict.items()
1002 items2 = dict.copy().items()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001003 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001004 "cloning of weak-keyed dictionary did not work!")
1005 del items1, items2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001006 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001007 del objects[0]
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001008 self.assertEqual(len(dict), (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001009 "deleting object did not cause dictionary update")
1010 del objects, o
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001011 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001012 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +00001013 o = Object(42)
1014 dict[o] = "What is the meaning of the universe?"
Benjamin Peterson577473f2010-01-19 00:09:57 +00001015 self.assertIn(o, dict)
1016 self.assertNotIn(34, dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +00001017
Fred Drake0e540c32001-05-02 05:44:22 +00001018 def test_weak_keyed_iters(self):
1019 dict, objects = self.make_weak_keyed_dict()
1020 self.check_iters(dict)
1021
Thomas Wouters477c8d52006-05-27 19:21:47 +00001022 # Test keyrefs()
1023 refs = dict.keyrefs()
1024 self.assertEqual(len(refs), len(objects))
1025 objects2 = list(objects)
1026 for wr in refs:
1027 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001028 self.assertIn(ob, dict)
1029 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001030 self.assertEqual(ob.arg, dict[ob])
1031 objects2.remove(ob)
1032 self.assertEqual(len(objects2), 0)
1033
1034 # Test iterkeyrefs()
1035 objects2 = list(objects)
Barry Warsawecaab832008-09-04 01:42:51 +00001036 self.assertEqual(len(list(dict.keyrefs())), len(objects))
1037 for wr in dict.keyrefs():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001038 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001039 self.assertIn(ob, dict)
1040 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001041 self.assertEqual(ob.arg, dict[ob])
1042 objects2.remove(ob)
1043 self.assertEqual(len(objects2), 0)
1044
Fred Drake0e540c32001-05-02 05:44:22 +00001045 def test_weak_valued_iters(self):
1046 dict, objects = self.make_weak_valued_dict()
1047 self.check_iters(dict)
1048
Thomas Wouters477c8d52006-05-27 19:21:47 +00001049 # Test valuerefs()
1050 refs = dict.valuerefs()
1051 self.assertEqual(len(refs), len(objects))
1052 objects2 = list(objects)
1053 for wr in refs:
1054 ob = wr()
1055 self.assertEqual(ob, dict[ob.arg])
1056 self.assertEqual(ob.arg, dict[ob.arg].arg)
1057 objects2.remove(ob)
1058 self.assertEqual(len(objects2), 0)
1059
1060 # Test itervaluerefs()
1061 objects2 = list(objects)
1062 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
1063 for wr in dict.itervaluerefs():
1064 ob = wr()
1065 self.assertEqual(ob, dict[ob.arg])
1066 self.assertEqual(ob.arg, dict[ob.arg].arg)
1067 objects2.remove(ob)
1068 self.assertEqual(len(objects2), 0)
1069
Fred Drake0e540c32001-05-02 05:44:22 +00001070 def check_iters(self, dict):
1071 # item iterator:
Barry Warsawecaab832008-09-04 01:42:51 +00001072 items = list(dict.items())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001073 for item in dict.items():
Fred Drake0e540c32001-05-02 05:44:22 +00001074 items.remove(item)
Barry Warsawecaab832008-09-04 01:42:51 +00001075 self.assertFalse(items, "items() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +00001076
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001077 # key iterator, via __iter__():
Guido van Rossum07f24362007-02-11 22:59:48 +00001078 keys = list(dict.keys())
Fred Drake0e540c32001-05-02 05:44:22 +00001079 for k in dict:
1080 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001081 self.assertFalse(keys, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001082
1083 # key iterator, via iterkeys():
Guido van Rossum07f24362007-02-11 22:59:48 +00001084 keys = list(dict.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001085 for k in dict.keys():
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001086 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001087 self.assertFalse(keys, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +00001088
1089 # value iterator:
Guido van Rossum07f24362007-02-11 22:59:48 +00001090 values = list(dict.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001091 for v in dict.values():
Fred Drake0e540c32001-05-02 05:44:22 +00001092 values.remove(v)
Barry Warsawecaab832008-09-04 01:42:51 +00001093 self.assertFalse(values,
Fred Drakef425b1e2003-07-14 21:37:17 +00001094 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +00001095
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001096 def check_weak_destroy_while_iterating(self, dict, objects, iter_name):
1097 n = len(dict)
1098 it = iter(getattr(dict, iter_name)())
1099 next(it) # Trigger internal iteration
1100 # Destroy an object
1101 del objects[-1]
1102 gc.collect() # just in case
1103 # We have removed either the first consumed object, or another one
1104 self.assertIn(len(list(it)), [len(objects), len(objects) - 1])
1105 del it
1106 # The removal has been committed
1107 self.assertEqual(len(dict), n - 1)
1108
1109 def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
1110 # Check that we can explicitly mutate the weak dict without
1111 # interfering with delayed removal.
1112 # `testcontext` should create an iterator, destroy one of the
1113 # weakref'ed objects and then return a new key/value pair corresponding
1114 # to the destroyed object.
1115 with testcontext() as (k, v):
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001116 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001117 with testcontext() as (k, v):
1118 self.assertRaises(KeyError, dict.__delitem__, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001119 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001120 with testcontext() as (k, v):
1121 self.assertRaises(KeyError, dict.pop, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001122 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001123 with testcontext() as (k, v):
1124 dict[k] = v
1125 self.assertEqual(dict[k], v)
1126 ddict = copy.copy(dict)
1127 with testcontext() as (k, v):
1128 dict.update(ddict)
1129 self.assertEqual(dict, ddict)
1130 with testcontext() as (k, v):
1131 dict.clear()
1132 self.assertEqual(len(dict), 0)
1133
1134 def test_weak_keys_destroy_while_iterating(self):
1135 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1136 dict, objects = self.make_weak_keyed_dict()
1137 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1138 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1139 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1140 self.check_weak_destroy_while_iterating(dict, objects, 'keyrefs')
1141 dict, objects = self.make_weak_keyed_dict()
1142 @contextlib.contextmanager
1143 def testcontext():
1144 try:
1145 it = iter(dict.items())
1146 next(it)
1147 # Schedule a key/value for removal and recreate it
1148 v = objects.pop().arg
1149 gc.collect() # just in case
1150 yield Object(v), v
1151 finally:
1152 it = None # should commit all removals
1153 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
1154
1155 def test_weak_values_destroy_while_iterating(self):
1156 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1157 dict, objects = self.make_weak_valued_dict()
1158 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1159 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1160 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1161 self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
1162 self.check_weak_destroy_while_iterating(dict, objects, 'valuerefs')
1163 dict, objects = self.make_weak_valued_dict()
1164 @contextlib.contextmanager
1165 def testcontext():
1166 try:
1167 it = iter(dict.items())
1168 next(it)
1169 # Schedule a key/value for removal and recreate it
1170 k = objects.pop().arg
1171 gc.collect() # just in case
1172 yield k, Object(k)
1173 finally:
1174 it = None # should commit all removals
1175 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
1176
Guido van Rossum009afb72002-06-10 20:00:52 +00001177 def test_make_weak_keyed_dict_from_dict(self):
1178 o = Object(3)
1179 dict = weakref.WeakKeyDictionary({o:364})
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001180 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001181
1182 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
1183 o = Object(3)
1184 dict = weakref.WeakKeyDictionary({o:364})
1185 dict2 = weakref.WeakKeyDictionary(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001186 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001187
Fred Drake0e540c32001-05-02 05:44:22 +00001188 def make_weak_keyed_dict(self):
1189 dict = weakref.WeakKeyDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001190 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001191 for o in objects:
1192 dict[o] = o.arg
1193 return dict, objects
1194
Antoine Pitrouc06de472009-05-30 21:04:26 +00001195 def test_make_weak_valued_dict_from_dict(self):
1196 o = Object(3)
1197 dict = weakref.WeakValueDictionary({364:o})
1198 self.assertEqual(dict[364], o)
1199
1200 def test_make_weak_valued_dict_from_weak_valued_dict(self):
1201 o = Object(3)
1202 dict = weakref.WeakValueDictionary({364:o})
1203 dict2 = weakref.WeakValueDictionary(dict)
1204 self.assertEqual(dict[364], o)
1205
Fred Drake0e540c32001-05-02 05:44:22 +00001206 def make_weak_valued_dict(self):
1207 dict = weakref.WeakValueDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001208 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001209 for o in objects:
1210 dict[o.arg] = o
1211 return dict, objects
1212
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001213 def check_popitem(self, klass, key1, value1, key2, value2):
1214 weakdict = klass()
1215 weakdict[key1] = value1
1216 weakdict[key2] = value2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001217 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001218 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001219 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001220 if k is key1:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001221 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001222 else:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001223 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001224 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001225 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001226 if k is key1:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001227 self.assertIs(v, value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001228 else:
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001229 self.assertIs(v, value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001230
1231 def test_weak_valued_dict_popitem(self):
1232 self.check_popitem(weakref.WeakValueDictionary,
1233 "key1", C(), "key2", C())
1234
1235 def test_weak_keyed_dict_popitem(self):
1236 self.check_popitem(weakref.WeakKeyDictionary,
1237 C(), "value 1", C(), "value 2")
1238
1239 def check_setdefault(self, klass, key, value1, value2):
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001240 self.assertIsNot(value1, value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001241 "invalid test"
1242 " -- value parameters must be distinct objects")
1243 weakdict = klass()
1244 o = weakdict.setdefault(key, value1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001245 self.assertIs(o, value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001246 self.assertIn(key, weakdict)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001247 self.assertIs(weakdict.get(key), value1)
1248 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001249
1250 o = weakdict.setdefault(key, value2)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001251 self.assertIs(o, value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001252 self.assertIn(key, weakdict)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001253 self.assertIs(weakdict.get(key), value1)
1254 self.assertIs(weakdict[key], value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001255
1256 def test_weak_valued_dict_setdefault(self):
1257 self.check_setdefault(weakref.WeakValueDictionary,
1258 "key", C(), C())
1259
1260 def test_weak_keyed_dict_setdefault(self):
1261 self.check_setdefault(weakref.WeakKeyDictionary,
1262 C(), "value 1", "value 2")
1263
Fred Drakea0a4ab12001-04-16 17:37:27 +00001264 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001265 #
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001266 # This exercises d.update(), len(d), d.keys(), k in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001267 # d.get(), d[].
1268 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001269 weakdict = klass()
1270 weakdict.update(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001271 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001272 for k in weakdict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001273 self.assertIn(k, dict, "mysterious new key appeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001274 v = dict.get(k)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001275 self.assertIs(v, weakdict[k])
1276 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001277 for k in dict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001278 self.assertIn(k, weakdict, "original key disappeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001279 v = dict[k]
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001280 self.assertIs(v, weakdict[k])
1281 self.assertIs(v, weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001282
1283 def test_weak_valued_dict_update(self):
1284 self.check_update(weakref.WeakValueDictionary,
1285 {1: C(), 'a': C(), C(): C()})
1286
1287 def test_weak_keyed_dict_update(self):
1288 self.check_update(weakref.WeakKeyDictionary,
1289 {C(): 1, C(): 2, C(): 3})
1290
Fred Drakeccc75622001-09-06 14:52:39 +00001291 def test_weak_keyed_delitem(self):
1292 d = weakref.WeakKeyDictionary()
1293 o1 = Object('1')
1294 o2 = Object('2')
1295 d[o1] = 'something'
1296 d[o2] = 'something'
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001297 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001298 del d[o1]
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001299 self.assertEqual(len(d), 1)
Barry Warsawecaab832008-09-04 01:42:51 +00001300 self.assertEqual(list(d.keys()), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001301
1302 def test_weak_valued_delitem(self):
1303 d = weakref.WeakValueDictionary()
1304 o1 = Object('1')
1305 o2 = Object('2')
1306 d['something'] = o1
1307 d['something else'] = o2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001308 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001309 del d['something']
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001310 self.assertEqual(len(d), 1)
Serhiy Storchaka2e29c9e2013-11-17 13:20:09 +02001311 self.assertEqual(list(d.items()), [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001312
Tim Peters886128f2003-05-25 01:45:11 +00001313 def test_weak_keyed_bad_delitem(self):
1314 d = weakref.WeakKeyDictionary()
1315 o = Object('1')
1316 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001317 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001318 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001319 self.assertRaises(KeyError, d.__getitem__, o)
1320
1321 # If a key isn't of a weakly referencable type, __getitem__ and
1322 # __setitem__ raise TypeError. __delitem__ should too.
1323 self.assertRaises(TypeError, d.__delitem__, 13)
1324 self.assertRaises(TypeError, d.__getitem__, 13)
1325 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001326
1327 def test_weak_keyed_cascading_deletes(self):
1328 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1329 # over the keys via self.data.iterkeys(). If things vanished from
1330 # the dict during this (or got added), that caused a RuntimeError.
1331
1332 d = weakref.WeakKeyDictionary()
1333 mutate = False
1334
1335 class C(object):
1336 def __init__(self, i):
1337 self.value = i
1338 def __hash__(self):
1339 return hash(self.value)
1340 def __eq__(self, other):
1341 if mutate:
1342 # Side effect that mutates the dict, by removing the
1343 # last strong reference to a key.
1344 del objs[-1]
1345 return self.value == other.value
1346
1347 objs = [C(i) for i in range(4)]
1348 for o in objs:
1349 d[o] = o.value
1350 del o # now the only strong references to keys are in objs
1351 # Find the order in which iterkeys sees the keys.
Barry Warsawecaab832008-09-04 01:42:51 +00001352 objs = list(d.keys())
Tim Peters886128f2003-05-25 01:45:11 +00001353 # Reverse it, so that the iteration implementation of __delitem__
1354 # has to keep looping to find the first object we delete.
1355 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001356
Tim Peters886128f2003-05-25 01:45:11 +00001357 # Turn on mutation in C.__eq__. The first time thru the loop,
1358 # under the iterkeys() business the first comparison will delete
1359 # the last item iterkeys() would see, and that causes a
1360 # RuntimeError: dictionary changed size during iteration
1361 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001362 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001363 # "for o in obj" loop would have gotten to.
1364 mutate = True
1365 count = 0
1366 for o in objs:
1367 count += 1
1368 del d[o]
1369 self.assertEqual(len(d), 0)
1370 self.assertEqual(count, 2)
1371
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001372from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001373
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001374class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001375 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001376 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001377 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001378 def _reference(self):
1379 return self.__ref.copy()
1380
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001381class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001382 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001383 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001384 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001385 def _reference(self):
1386 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001387
Georg Brandlb533e262008-05-25 18:19:30 +00001388libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00001389
1390>>> import weakref
1391>>> class Dict(dict):
1392... pass
1393...
1394>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1395>>> r = weakref.ref(obj)
Guido van Rossum7131f842007-02-09 20:13:25 +00001396>>> print(r() is obj)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001397True
Georg Brandl9a65d582005-07-02 19:07:30 +00001398
1399>>> import weakref
1400>>> class Object:
1401... pass
1402...
1403>>> o = Object()
1404>>> r = weakref.ref(o)
1405>>> o2 = r()
1406>>> o is o2
1407True
1408>>> del o, o2
Guido van Rossum7131f842007-02-09 20:13:25 +00001409>>> print(r())
Georg Brandl9a65d582005-07-02 19:07:30 +00001410None
1411
1412>>> import weakref
1413>>> class ExtendedRef(weakref.ref):
1414... def __init__(self, ob, callback=None, **annotations):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001415... super().__init__(ob, callback)
Georg Brandl9a65d582005-07-02 19:07:30 +00001416... self.__counter = 0
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001417... for k, v in annotations.items():
Georg Brandl9a65d582005-07-02 19:07:30 +00001418... setattr(self, k, v)
1419... def __call__(self):
1420... '''Return a pair containing the referent and the number of
1421... times the reference has been called.
1422... '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001423... ob = super().__call__()
Georg Brandl9a65d582005-07-02 19:07:30 +00001424... if ob is not None:
1425... self.__counter += 1
1426... ob = (ob, self.__counter)
1427... return ob
Guido van Rossumd8faa362007-04-27 19:54:29 +00001428...
Georg Brandl9a65d582005-07-02 19:07:30 +00001429>>> class A: # not in docs from here, just testing the ExtendedRef
1430... pass
1431...
1432>>> a = A()
1433>>> r = ExtendedRef(a, foo=1, bar="baz")
1434>>> r.foo
14351
1436>>> r.bar
1437'baz'
1438>>> r()[1]
14391
1440>>> r()[1]
14412
1442>>> r()[0] is a
1443True
1444
1445
1446>>> import weakref
1447>>> _id2obj_dict = weakref.WeakValueDictionary()
1448>>> def remember(obj):
1449... oid = id(obj)
1450... _id2obj_dict[oid] = obj
1451... return oid
1452...
1453>>> def id2obj(oid):
1454... return _id2obj_dict[oid]
1455...
1456>>> a = A() # from here, just testing
1457>>> a_id = remember(a)
1458>>> id2obj(a_id) is a
1459True
1460>>> del a
1461>>> try:
1462... id2obj(a_id)
1463... except KeyError:
Guido van Rossum7131f842007-02-09 20:13:25 +00001464... print('OK')
Georg Brandl9a65d582005-07-02 19:07:30 +00001465... else:
Guido van Rossum7131f842007-02-09 20:13:25 +00001466... print('WeakValueDictionary error')
Georg Brandl9a65d582005-07-02 19:07:30 +00001467OK
1468
1469"""
1470
1471__test__ = {'libreftest' : libreftest}
1472
Fred Drake2e2be372001-09-20 21:33:42 +00001473def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001474 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +00001475 ReferencesTestCase,
1476 MappingTestCase,
1477 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001478 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00001479 SubclassableWeakrefTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001480 )
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001481 support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001482
1483
1484if __name__ == "__main__":
1485 test_main()