blob: 571e33f492d4b825fc0b19308759c69da041b68c [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
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000091 self.assertTrue(ref1() is None,
Fred Drakeb0fefc52001-03-23 04:22:45 +000092 "expected reference to be invalidated")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000093 self.assertTrue(ref2() is None,
Fred Drakeb0fefc52001-03-23 04:22:45 +000094 "expected reference to be invalidated")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000095 self.assertTrue(self.cbcalled == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +000096 "callback not called the right number of times")
Fred Drake41deb1e2001-02-01 05:27:45 +000097
Fred Drake705088e2001-04-13 17:18:15 +000098 def test_multiple_selfref_callbacks(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +000099 # Make sure all references are invalidated before callbacks are called
Fred Drake705088e2001-04-13 17:18:15 +0000100 #
101 # What's important here is that we're using the first
102 # reference in the callback invoked on the second reference
103 # (the most recently created ref is cleaned up first). This
104 # tests that all references to the object are invalidated
105 # before any of the callbacks are invoked, so that we only
106 # have one invocation of _weakref.c:cleanup_helper() active
107 # for a particular object at a time.
108 #
109 def callback(object, self=self):
110 self.ref()
111 c = C()
112 self.ref = weakref.ref(c, callback)
113 ref1 = weakref.ref(c, callback)
114 del c
115
Fred Drakeb0fefc52001-03-23 04:22:45 +0000116 def test_proxy_ref(self):
117 o = C()
118 o.bar = 1
119 ref1 = weakref.proxy(o, self.callback)
120 ref2 = weakref.proxy(o, self.callback)
121 del o
Fred Drake41deb1e2001-02-01 05:27:45 +0000122
Fred Drakeb0fefc52001-03-23 04:22:45 +0000123 def check(proxy):
124 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000125
Neal Norwitz2633c692007-02-26 22:22:47 +0000126 self.assertRaises(ReferenceError, check, ref1)
127 self.assertRaises(ReferenceError, check, ref2)
128 self.assertRaises(ReferenceError, bool, weakref.proxy(C()))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000129 self.assertEqual(self.cbcalled, 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000130
Fred Drakeb0fefc52001-03-23 04:22:45 +0000131 def check_basic_ref(self, factory):
132 o = factory()
133 ref = weakref.ref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000134 self.assertTrue(ref() is not None,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000135 "weak reference to live object should be live")
136 o2 = ref()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000137 self.assertTrue(o is o2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000138 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000139
Fred Drakeb0fefc52001-03-23 04:22:45 +0000140 def check_basic_callback(self, factory):
141 self.cbcalled = 0
142 o = factory()
143 ref = weakref.ref(o, self.callback)
144 del o
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000145 self.assertTrue(self.cbcalled == 1,
Fred Drake705088e2001-04-13 17:18:15 +0000146 "callback did not properly set 'cbcalled'")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000147 self.assertTrue(ref() is None,
Fred Drake705088e2001-04-13 17:18:15 +0000148 "ref2 should be dead after deleting object reference")
Fred Drake41deb1e2001-02-01 05:27:45 +0000149
Fred Drakeb0fefc52001-03-23 04:22:45 +0000150 def test_ref_reuse(self):
151 o = C()
152 ref1 = weakref.ref(o)
153 # create a proxy to make sure that there's an intervening creation
154 # between these two; it should make no difference
155 proxy = weakref.proxy(o)
156 ref2 = weakref.ref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000157 self.assertTrue(ref1 is ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000158 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000159
Fred Drakeb0fefc52001-03-23 04:22:45 +0000160 o = C()
161 proxy = weakref.proxy(o)
162 ref1 = weakref.ref(o)
163 ref2 = weakref.ref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000164 self.assertTrue(ref1 is ref2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000165 "reference object w/out callback should be re-used")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000166 self.assertTrue(weakref.getweakrefcount(o) == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000167 "wrong weak ref count for object")
168 del proxy
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000169 self.assertTrue(weakref.getweakrefcount(o) == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000170 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000171
Fred Drakeb0fefc52001-03-23 04:22:45 +0000172 def test_proxy_reuse(self):
173 o = C()
174 proxy1 = weakref.proxy(o)
175 ref = weakref.ref(o)
176 proxy2 = weakref.proxy(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000177 self.assertTrue(proxy1 is proxy2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000178 "proxy object w/out callback should have been re-used")
179
180 def test_basic_proxy(self):
181 o = C()
182 self.check_proxy(o, weakref.proxy(o))
183
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000184 L = collections.UserList()
Fred Drake5935ff02001-12-19 16:54:23 +0000185 p = weakref.proxy(L)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000186 self.assertFalse(p, "proxy for empty UserList should be false")
Fred Drake5935ff02001-12-19 16:54:23 +0000187 p.append(12)
188 self.assertEqual(len(L), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000189 self.assertTrue(p, "proxy for non-empty UserList should be true")
Fred Drake5935ff02001-12-19 16:54:23 +0000190 p[:] = [2, 3]
191 self.assertEqual(len(L), 2)
192 self.assertEqual(len(p), 2)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000193 self.assertIn(3, p, "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000194 p[1] = 5
195 self.assertEqual(L[1], 5)
196 self.assertEqual(p[1], 5)
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000197 L2 = collections.UserList(L)
Fred Drake5935ff02001-12-19 16:54:23 +0000198 p2 = weakref.proxy(L2)
199 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000200 ## self.assertEqual(repr(L2), repr(p2))
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000201 L3 = collections.UserList(range(10))
Fred Drake43735da2002-04-11 03:59:42 +0000202 p3 = weakref.proxy(L3)
203 self.assertEqual(L3[:], p3[:])
204 self.assertEqual(L3[5:], p3[5:])
205 self.assertEqual(L3[:5], p3[:5])
206 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000207
Benjamin Peterson32019772009-11-19 03:08:32 +0000208 def test_proxy_unicode(self):
209 # See bug 5037
210 class C(object):
211 def __str__(self):
212 return "string"
213 def __bytes__(self):
214 return b"bytes"
215 instance = C()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000216 self.assertIn("__bytes__", dir(weakref.proxy(instance)))
Benjamin Peterson32019772009-11-19 03:08:32 +0000217 self.assertEqual(bytes(weakref.proxy(instance)), b"bytes")
218
Georg Brandlb533e262008-05-25 18:19:30 +0000219 def test_proxy_index(self):
220 class C:
221 def __index__(self):
222 return 10
223 o = C()
224 p = weakref.proxy(o)
225 self.assertEqual(operator.index(p), 10)
226
227 def test_proxy_div(self):
228 class C:
229 def __floordiv__(self, other):
230 return 42
231 def __ifloordiv__(self, other):
232 return 21
233 o = C()
234 p = weakref.proxy(o)
235 self.assertEqual(p // 5, 42)
236 p //= 5
237 self.assertEqual(p, 21)
238
Fred Drakeea2adc92004-02-03 19:56:46 +0000239 # The PyWeakref_* C API is documented as allowing either NULL or
240 # None as the value for the callback, where either means "no
241 # callback". The "no callback" ref and proxy objects are supposed
242 # to be shared so long as they exist by all callers so long as
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000243 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000244 # was not honored, and was broken in different ways for
245 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
246
247 def test_shared_ref_without_callback(self):
248 self.check_shared_without_callback(weakref.ref)
249
250 def test_shared_proxy_without_callback(self):
251 self.check_shared_without_callback(weakref.proxy)
252
253 def check_shared_without_callback(self, makeref):
254 o = Object(1)
255 p1 = makeref(o, None)
256 p2 = makeref(o, None)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000257 self.assertTrue(p1 is p2, "both callbacks were None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000258 del p1, p2
259 p1 = makeref(o)
260 p2 = makeref(o, None)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000261 self.assertTrue(p1 is p2, "callbacks were NULL, None in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000262 del p1, p2
263 p1 = makeref(o)
264 p2 = makeref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000265 self.assertTrue(p1 is p2, "both callbacks were NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000266 del p1, p2
267 p1 = makeref(o, None)
268 p2 = makeref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000269 self.assertTrue(p1 is p2, "callbacks were None, NULL in the C API")
Fred Drakeea2adc92004-02-03 19:56:46 +0000270
Fred Drakeb0fefc52001-03-23 04:22:45 +0000271 def test_callable_proxy(self):
272 o = Callable()
273 ref1 = weakref.proxy(o)
274
275 self.check_proxy(o, ref1)
276
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000277 self.assertTrue(type(ref1) is weakref.CallableProxyType,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000278 "proxy is not of callable type")
279 ref1('twinkies!')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000280 self.assertTrue(o.bar == 'twinkies!',
Fred Drakeb0fefc52001-03-23 04:22:45 +0000281 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000282 ref1(x='Splat.')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000283 self.assertTrue(o.bar == 'Splat.',
Fred Drake3bb4d212001-10-18 19:28:29 +0000284 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000285
286 # expect due to too few args
287 self.assertRaises(TypeError, ref1)
288
289 # expect due to too many args
290 self.assertRaises(TypeError, ref1, 1, 2, 3)
291
292 def check_proxy(self, o, proxy):
293 o.foo = 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000294 self.assertTrue(proxy.foo == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000295 "proxy does not reflect attribute addition")
296 o.foo = 2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000297 self.assertTrue(proxy.foo == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000298 "proxy does not reflect attribute modification")
299 del o.foo
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000300 self.assertTrue(not hasattr(proxy, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000301 "proxy does not reflect attribute removal")
302
303 proxy.foo = 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000304 self.assertTrue(o.foo == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000305 "object does not reflect attribute addition via proxy")
306 proxy.foo = 2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000307 self.assertTrue(
Fred Drakeb0fefc52001-03-23 04:22:45 +0000308 o.foo == 2,
309 "object does not reflect attribute modification via proxy")
310 del proxy.foo
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000311 self.assertTrue(not hasattr(o, 'foo'),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000312 "object does not reflect attribute removal via proxy")
313
Raymond Hettingerd693a812003-06-30 04:18:48 +0000314 def test_proxy_deletion(self):
315 # Test clearing of SF bug #762891
316 class Foo:
317 result = None
318 def __delitem__(self, accessor):
319 self.result = accessor
320 g = Foo()
321 f = weakref.proxy(g)
322 del f[0]
323 self.assertEqual(f.result, 0)
324
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000325 def test_proxy_bool(self):
326 # Test clearing of SF bug #1170766
327 class List(list): pass
328 lyst = List()
329 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
330
Fred Drakeb0fefc52001-03-23 04:22:45 +0000331 def test_getweakrefcount(self):
332 o = C()
333 ref1 = weakref.ref(o)
334 ref2 = weakref.ref(o, self.callback)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000335 self.assertTrue(weakref.getweakrefcount(o) == 2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000336 "got wrong number of weak reference objects")
337
338 proxy1 = weakref.proxy(o)
339 proxy2 = weakref.proxy(o, self.callback)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000340 self.assertTrue(weakref.getweakrefcount(o) == 4,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000341 "got wrong number of weak reference objects")
342
Fred Drakeea2adc92004-02-03 19:56:46 +0000343 del ref1, ref2, proxy1, proxy2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000344 self.assertTrue(weakref.getweakrefcount(o) == 0,
Fred Drakeea2adc92004-02-03 19:56:46 +0000345 "weak reference objects not unlinked from"
346 " referent when discarded.")
347
Walter Dörwaldb167b042003-12-11 12:34:05 +0000348 # assumes ints do not support weakrefs
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000349 self.assertTrue(weakref.getweakrefcount(1) == 0,
Walter Dörwaldb167b042003-12-11 12:34:05 +0000350 "got wrong number of weak reference objects for int")
351
Fred Drakeb0fefc52001-03-23 04:22:45 +0000352 def test_getweakrefs(self):
353 o = C()
354 ref1 = weakref.ref(o, self.callback)
355 ref2 = weakref.ref(o, self.callback)
356 del ref1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000357 self.assertTrue(weakref.getweakrefs(o) == [ref2],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000358 "list of refs does not match")
359
360 o = C()
361 ref1 = weakref.ref(o, self.callback)
362 ref2 = weakref.ref(o, self.callback)
363 del ref2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000364 self.assertTrue(weakref.getweakrefs(o) == [ref1],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000365 "list of refs does not match")
366
Fred Drakeea2adc92004-02-03 19:56:46 +0000367 del ref1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000368 self.assertTrue(weakref.getweakrefs(o) == [],
Fred Drakeea2adc92004-02-03 19:56:46 +0000369 "list of refs not cleared")
370
Walter Dörwaldb167b042003-12-11 12:34:05 +0000371 # assumes ints do not support weakrefs
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000372 self.assertTrue(weakref.getweakrefs(1) == [],
Walter Dörwaldb167b042003-12-11 12:34:05 +0000373 "list of refs does not match for int")
374
Fred Drake39c27f12001-10-18 18:06:05 +0000375 def test_newstyle_number_ops(self):
376 class F(float):
377 pass
378 f = F(2.0)
379 p = weakref.proxy(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000380 self.assertTrue(p + 1.0 == 3.0)
381 self.assertTrue(1.0 + p == 3.0) # this used to SEGV
Fred Drake39c27f12001-10-18 18:06:05 +0000382
Fred Drake2a64f462001-12-10 23:46:02 +0000383 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000384 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000385 # Regression test for SF bug #478534.
386 class BogusError(Exception):
387 pass
388 data = {}
389 def remove(k):
390 del data[k]
391 def encapsulate():
392 f = lambda : ()
393 data[weakref.ref(f, remove)] = None
394 raise BogusError
395 try:
396 encapsulate()
397 except BogusError:
398 pass
399 else:
400 self.fail("exception not properly restored")
401 try:
402 encapsulate()
403 except BogusError:
404 pass
405 else:
406 self.fail("exception not properly restored")
407
Tim Petersadd09b42003-11-12 20:43:28 +0000408 def test_sf_bug_840829(self):
409 # "weakref callbacks and gc corrupt memory"
410 # subtype_dealloc erroneously exposed a new-style instance
411 # already in the process of getting deallocated to gc,
412 # causing double-deallocation if the instance had a weakref
413 # callback that triggered gc.
414 # If the bug exists, there probably won't be an obvious symptom
415 # in a release build. In a debug build, a segfault will occur
416 # when the second attempt to remove the instance from the "list
417 # of all objects" occurs.
418
419 import gc
420
421 class C(object):
422 pass
423
424 c = C()
425 wr = weakref.ref(c, lambda ignore: gc.collect())
426 del c
427
Tim Petersf7f9e992003-11-13 21:59:32 +0000428 # There endeth the first part. It gets worse.
429 del wr
430
431 c1 = C()
432 c1.i = C()
433 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
434
435 c2 = C()
436 c2.c1 = c1
437 del c1 # still alive because c2 points to it
438
439 # Now when subtype_dealloc gets called on c2, it's not enough just
440 # that c2 is immune from gc while the weakref callbacks associated
441 # with c2 execute (there are none in this 2nd half of the test, btw).
442 # subtype_dealloc goes on to call the base classes' deallocs too,
443 # so any gc triggered by weakref callbacks associated with anything
444 # torn down by a base class dealloc can also trigger double
445 # deallocation of c2.
446 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000447
Tim Peters403a2032003-11-20 21:21:46 +0000448 def test_callback_in_cycle_1(self):
449 import gc
450
451 class J(object):
452 pass
453
454 class II(object):
455 def acallback(self, ignore):
456 self.J
457
458 I = II()
459 I.J = J
460 I.wr = weakref.ref(J, I.acallback)
461
462 # Now J and II are each in a self-cycle (as all new-style class
463 # objects are, since their __mro__ points back to them). I holds
464 # both a weak reference (I.wr) and a strong reference (I.J) to class
465 # J. I is also in a cycle (I.wr points to a weakref that references
466 # I.acallback). When we del these three, they all become trash, but
467 # the cycles prevent any of them from getting cleaned up immediately.
468 # Instead they have to wait for cyclic gc to deduce that they're
469 # trash.
470 #
471 # gc used to call tp_clear on all of them, and the order in which
472 # it does that is pretty accidental. The exact order in which we
473 # built up these things manages to provoke gc into running tp_clear
474 # in just the right order (I last). Calling tp_clear on II leaves
475 # behind an insane class object (its __mro__ becomes NULL). Calling
476 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
477 # just then because of the strong reference from I.J. Calling
478 # tp_clear on I starts to clear I's __dict__, and just happens to
479 # clear I.J first -- I.wr is still intact. That removes the last
480 # reference to J, which triggers the weakref callback. The callback
481 # tries to do "self.J", and instances of new-style classes look up
482 # attributes ("J") in the class dict first. The class (II) wants to
483 # search II.__mro__, but that's NULL. The result was a segfault in
484 # a release build, and an assert failure in a debug build.
485 del I, J, II
486 gc.collect()
487
488 def test_callback_in_cycle_2(self):
489 import gc
490
491 # This is just like test_callback_in_cycle_1, except that II is an
492 # old-style class. The symptom is different then: an instance of an
493 # old-style class looks in its own __dict__ first. 'J' happens to
494 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
495 # __dict__, so the attribute isn't found. The difference is that
496 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
497 # __mro__), so no segfault occurs. Instead it got:
498 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
499 # Exception exceptions.AttributeError:
500 # "II instance has no attribute 'J'" in <bound method II.acallback
501 # of <?.II instance at 0x00B9B4B8>> ignored
502
503 class J(object):
504 pass
505
506 class II:
507 def acallback(self, ignore):
508 self.J
509
510 I = II()
511 I.J = J
512 I.wr = weakref.ref(J, I.acallback)
513
514 del I, J, II
515 gc.collect()
516
517 def test_callback_in_cycle_3(self):
518 import gc
519
520 # This one broke the first patch that fixed the last two. In this
521 # case, the objects reachable from the callback aren't also reachable
522 # from the object (c1) *triggering* the callback: you can get to
523 # c1 from c2, but not vice-versa. The result was that c2's __dict__
524 # got tp_clear'ed by the time the c2.cb callback got invoked.
525
526 class C:
527 def cb(self, ignore):
528 self.me
529 self.c1
530 self.wr
531
532 c1, c2 = C(), C()
533
534 c2.me = c2
535 c2.c1 = c1
536 c2.wr = weakref.ref(c1, c2.cb)
537
538 del c1, c2
539 gc.collect()
540
541 def test_callback_in_cycle_4(self):
542 import gc
543
544 # Like test_callback_in_cycle_3, except c2 and c1 have different
545 # classes. c2's class (C) isn't reachable from c1 then, so protecting
546 # objects reachable from the dying object (c1) isn't enough to stop
547 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
548 # The result was a segfault (C.__mro__ was NULL when the callback
549 # tried to look up self.me).
550
551 class C(object):
552 def cb(self, ignore):
553 self.me
554 self.c1
555 self.wr
556
557 class D:
558 pass
559
560 c1, c2 = D(), C()
561
562 c2.me = c2
563 c2.c1 = c1
564 c2.wr = weakref.ref(c1, c2.cb)
565
566 del c1, c2, C, D
567 gc.collect()
568
569 def test_callback_in_cycle_resurrection(self):
570 import gc
571
572 # Do something nasty in a weakref callback: resurrect objects
573 # from dead cycles. For this to be attempted, the weakref and
574 # its callback must also be part of the cyclic trash (else the
575 # objects reachable via the callback couldn't be in cyclic trash
576 # to begin with -- the callback would act like an external root).
577 # But gc clears trash weakrefs with callbacks early now, which
578 # disables the callbacks, so the callbacks shouldn't get called
579 # at all (and so nothing actually gets resurrected).
580
581 alist = []
582 class C(object):
583 def __init__(self, value):
584 self.attribute = value
585
586 def acallback(self, ignore):
587 alist.append(self.c)
588
589 c1, c2 = C(1), C(2)
590 c1.c = c2
591 c2.c = c1
592 c1.wr = weakref.ref(c2, c1.acallback)
593 c2.wr = weakref.ref(c1, c2.acallback)
594
595 def C_went_away(ignore):
596 alist.append("C went away")
597 wr = weakref.ref(C, C_went_away)
598
599 del c1, c2, C # make them all trash
600 self.assertEqual(alist, []) # del isn't enough to reclaim anything
601
602 gc.collect()
603 # c1.wr and c2.wr were part of the cyclic trash, so should have
604 # been cleared without their callbacks executing. OTOH, the weakref
605 # to C is bound to a function local (wr), and wasn't trash, so that
606 # callback should have been invoked when C went away.
607 self.assertEqual(alist, ["C went away"])
608 # The remaining weakref should be dead now (its callback ran).
609 self.assertEqual(wr(), None)
610
611 del alist[:]
612 gc.collect()
613 self.assertEqual(alist, [])
614
615 def test_callbacks_on_callback(self):
616 import gc
617
618 # Set up weakref callbacks *on* weakref callbacks.
619 alist = []
620 def safe_callback(ignore):
621 alist.append("safe_callback called")
622
623 class C(object):
624 def cb(self, ignore):
625 alist.append("cb called")
626
627 c, d = C(), C()
628 c.other = d
629 d.other = c
630 callback = c.cb
631 c.wr = weakref.ref(d, callback) # this won't trigger
632 d.wr = weakref.ref(callback, d.cb) # ditto
633 external_wr = weakref.ref(callback, safe_callback) # but this will
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000634 self.assertTrue(external_wr() is callback)
Tim Peters403a2032003-11-20 21:21:46 +0000635
636 # The weakrefs attached to c and d should get cleared, so that
637 # C.cb is never called. But external_wr isn't part of the cyclic
638 # trash, and no cyclic trash is reachable from it, so safe_callback
639 # should get invoked when the bound method object callback (c.cb)
640 # -- which is itself a callback, and also part of the cyclic trash --
641 # gets reclaimed at the end of gc.
642
643 del callback, c, d, C
644 self.assertEqual(alist, []) # del isn't enough to clean up cycles
645 gc.collect()
646 self.assertEqual(alist, ["safe_callback called"])
647 self.assertEqual(external_wr(), None)
648
649 del alist[:]
650 gc.collect()
651 self.assertEqual(alist, [])
652
Fred Drakebc875f52004-02-04 23:14:14 +0000653 def test_gc_during_ref_creation(self):
654 self.check_gc_during_creation(weakref.ref)
655
656 def test_gc_during_proxy_creation(self):
657 self.check_gc_during_creation(weakref.proxy)
658
659 def check_gc_during_creation(self, makeref):
660 thresholds = gc.get_threshold()
661 gc.set_threshold(1, 1, 1)
662 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000663 class A:
664 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000665
666 def callback(*args):
667 pass
668
Fred Drake55cf4342004-02-13 19:21:57 +0000669 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000670
Fred Drake55cf4342004-02-13 19:21:57 +0000671 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000672 a.a = a
673 a.wr = makeref(referenced)
674
675 try:
676 # now make sure the object and the ref get labeled as
677 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000678 a = A()
679 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000680
681 finally:
682 gc.set_threshold(*thresholds)
683
Thomas Woutersb2137042007-02-01 18:02:27 +0000684 def test_ref_created_during_del(self):
685 # Bug #1377858
686 # A weakref created in an object's __del__() would crash the
687 # interpreter when the weakref was cleaned up since it would refer to
688 # non-existent memory. This test should not segfault the interpreter.
689 class Target(object):
690 def __del__(self):
691 global ref_from_del
692 ref_from_del = weakref.ref(self)
693
694 w = Target()
695
Benjamin Peterson9aa42992008-09-10 21:57:34 +0000696 def test_init(self):
697 # Issue 3634
698 # <weakref to class>.__init__() doesn't check errors correctly
699 r = weakref.ref(Exception)
700 self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
701 # No exception should be raised here
702 gc.collect()
703
Antoine Pitrou3af01a12010-03-31 21:40:47 +0000704 def test_classes(self):
705 # Check that classes are weakrefable.
706 class A(object):
707 pass
708 l = []
709 weakref.ref(int)
710 a = weakref.ref(A, l.append)
711 A = None
712 gc.collect()
713 self.assertEqual(a(), None)
714 self.assertEqual(l, [a])
715
Antoine Pitroue11fecb2012-11-11 19:36:51 +0100716 def test_equality(self):
717 # Alive weakrefs defer equality testing to their underlying object.
718 x = Object(1)
719 y = Object(1)
720 z = Object(2)
721 a = weakref.ref(x)
722 b = weakref.ref(y)
723 c = weakref.ref(z)
724 d = weakref.ref(x)
725 # Note how we directly test the operators here, to stress both
726 # __eq__ and __ne__.
727 self.assertTrue(a == b)
728 self.assertFalse(a != b)
729 self.assertFalse(a == c)
730 self.assertTrue(a != c)
731 self.assertTrue(a == d)
732 self.assertFalse(a != d)
733 del x, y, z
734 gc.collect()
735 for r in a, b, c:
736 # Sanity check
737 self.assertIs(r(), None)
738 # Dead weakrefs compare by identity: whether `a` and `d` are the
739 # same weakref object is an implementation detail, since they pointed
740 # to the same original object and didn't have a callback.
741 # (see issue #16453).
742 self.assertFalse(a == b)
743 self.assertTrue(a != b)
744 self.assertFalse(a == c)
745 self.assertTrue(a != c)
746 self.assertEqual(a == d, a is d)
747 self.assertEqual(a != d, a is not d)
748
749 def test_ordering(self):
750 # weakrefs cannot be ordered, even if the underlying objects can.
751 ops = [operator.lt, operator.gt, operator.le, operator.ge]
752 x = Object(1)
753 y = Object(1)
754 a = weakref.ref(x)
755 b = weakref.ref(y)
756 for op in ops:
757 self.assertRaises(TypeError, op, a, b)
758 # Same when dead.
759 del x, y
760 gc.collect()
761 for op in ops:
762 self.assertRaises(TypeError, op, a, b)
763
764 def test_hashing(self):
765 # Alive weakrefs hash the same as the underlying object
766 x = Object(42)
767 y = Object(42)
768 a = weakref.ref(x)
769 b = weakref.ref(y)
770 self.assertEqual(hash(a), hash(42))
771 del x, y
772 gc.collect()
773 # Dead weakrefs:
774 # - retain their hash is they were hashed when alive;
775 # - otherwise, cannot be hashed.
776 self.assertEqual(hash(a), hash(42))
777 self.assertRaises(TypeError, hash, b)
778
Antoine Pitrou62a0d6e2012-12-08 21:15:26 +0100779 def test_trashcan_16602(self):
780 # Issue #16602: when a weakref's target was part of a long
781 # deallocation chain, the trashcan mechanism could delay clearing
782 # of the weakref and make the target object visible from outside
783 # code even though its refcount had dropped to 0. A crash ensued.
784 class C:
785 def __init__(self, parent):
786 if not parent:
787 return
788 wself = weakref.ref(self)
789 def cb(wparent):
790 o = wself()
791 self.wparent = weakref.ref(parent, cb)
792
793 d = weakref.WeakKeyDictionary()
794 root = c = C(None)
795 for n in range(100):
796 d[c] = c = C(c)
797 del root
798 gc.collect()
799
Fred Drake0a4dd392004-07-02 18:57:45 +0000800
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000801class SubclassableWeakrefTestCase(TestBase):
Fred Drake0a4dd392004-07-02 18:57:45 +0000802
803 def test_subclass_refs(self):
804 class MyRef(weakref.ref):
805 def __init__(self, ob, callback=None, value=42):
806 self.value = value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000807 super().__init__(ob, callback)
Fred Drake0a4dd392004-07-02 18:57:45 +0000808 def __call__(self):
809 self.called = True
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000810 return super().__call__()
Fred Drake0a4dd392004-07-02 18:57:45 +0000811 o = Object("foo")
812 mr = MyRef(o, value=24)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000813 self.assertTrue(mr() is o)
814 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000815 self.assertEqual(mr.value, 24)
816 del o
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000817 self.assertTrue(mr() is None)
818 self.assertTrue(mr.called)
Fred Drake0a4dd392004-07-02 18:57:45 +0000819
820 def test_subclass_refs_dont_replace_standard_refs(self):
821 class MyRef(weakref.ref):
822 pass
823 o = Object(42)
824 r1 = MyRef(o)
825 r2 = weakref.ref(o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000826 self.assertTrue(r1 is not r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000827 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
828 self.assertEqual(weakref.getweakrefcount(o), 2)
829 r3 = MyRef(o)
830 self.assertEqual(weakref.getweakrefcount(o), 3)
831 refs = weakref.getweakrefs(o)
832 self.assertEqual(len(refs), 3)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000833 self.assertTrue(r2 is refs[0])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000834 self.assertIn(r1, refs[1:])
835 self.assertIn(r3, refs[1:])
Fred Drake0a4dd392004-07-02 18:57:45 +0000836
837 def test_subclass_refs_dont_conflate_callbacks(self):
838 class MyRef(weakref.ref):
839 pass
840 o = Object(42)
841 r1 = MyRef(o, id)
842 r2 = MyRef(o, str)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000843 self.assertTrue(r1 is not r2)
Fred Drake0a4dd392004-07-02 18:57:45 +0000844 refs = weakref.getweakrefs(o)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000845 self.assertIn(r1, refs)
846 self.assertIn(r2, refs)
Fred Drake0a4dd392004-07-02 18:57:45 +0000847
848 def test_subclass_refs_with_slots(self):
849 class MyRef(weakref.ref):
850 __slots__ = "slot1", "slot2"
851 def __new__(type, ob, callback, slot1, slot2):
852 return weakref.ref.__new__(type, ob, callback)
853 def __init__(self, ob, callback, slot1, slot2):
854 self.slot1 = slot1
855 self.slot2 = slot2
856 def meth(self):
857 return self.slot1 + self.slot2
858 o = Object(42)
859 r = MyRef(o, None, "abc", "def")
860 self.assertEqual(r.slot1, "abc")
861 self.assertEqual(r.slot2, "def")
862 self.assertEqual(r.meth(), "abcdef")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000863 self.assertFalse(hasattr(r, "__dict__"))
Fred Drake0a4dd392004-07-02 18:57:45 +0000864
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +0000865 def test_subclass_refs_with_cycle(self):
866 # Bug #3110
867 # An instance of a weakref subclass can have attributes.
868 # If such a weakref holds the only strong reference to the object,
869 # deleting the weakref will delete the object. In this case,
870 # the callback must not be called, because the ref object is
871 # being deleted.
872 class MyRef(weakref.ref):
873 pass
874
875 # Use a local callback, for "regrtest -R::"
876 # to detect refcounting problems
877 def callback(w):
878 self.cbcalled += 1
879
880 o = C()
881 r1 = MyRef(o, callback)
882 r1.o = o
883 del o
884
885 del r1 # Used to crash here
886
887 self.assertEqual(self.cbcalled, 0)
888
889 # Same test, with two weakrefs to the same object
890 # (since code paths are different)
891 o = C()
892 r1 = MyRef(o, callback)
893 r2 = MyRef(o, callback)
894 r1.r = r2
895 r2.o = o
896 del o
897 del r2
898
899 del r1 # Used to crash here
900
901 self.assertEqual(self.cbcalled, 0)
902
Fred Drake0a4dd392004-07-02 18:57:45 +0000903
Fred Drakeb0fefc52001-03-23 04:22:45 +0000904class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000905
Fred Drakeb0fefc52001-03-23 04:22:45 +0000906 COUNT = 10
907
Antoine Pitroubbe2f602012-03-01 16:26:35 +0100908 def check_len_cycles(self, dict_type, cons):
909 N = 20
910 items = [RefCycle() for i in range(N)]
911 dct = dict_type(cons(o) for o in items)
912 # Keep an iterator alive
913 it = dct.items()
914 try:
915 next(it)
916 except StopIteration:
917 pass
918 del items
919 gc.collect()
920 n1 = len(dct)
921 del it
922 gc.collect()
923 n2 = len(dct)
924 # one item may be kept alive inside the iterator
925 self.assertIn(n1, (0, 1))
926 self.assertEqual(n2, 0)
927
928 def test_weak_keyed_len_cycles(self):
929 self.check_len_cycles(weakref.WeakKeyDictionary, lambda k: (k, 1))
930
931 def test_weak_valued_len_cycles(self):
932 self.check_len_cycles(weakref.WeakValueDictionary, lambda k: (1, k))
933
934 def check_len_race(self, dict_type, cons):
935 # Extended sanity checks for len() in the face of cyclic collection
936 self.addCleanup(gc.set_threshold, *gc.get_threshold())
937 for th in range(1, 100):
938 N = 20
939 gc.collect(0)
940 gc.set_threshold(th, th, th)
941 items = [RefCycle() for i in range(N)]
942 dct = dict_type(cons(o) for o in items)
943 del items
944 # All items will be collected at next garbage collection pass
945 it = dct.items()
946 try:
947 next(it)
948 except StopIteration:
949 pass
950 n1 = len(dct)
951 del it
952 n2 = len(dct)
953 self.assertGreaterEqual(n1, 0)
954 self.assertLessEqual(n1, N)
955 self.assertGreaterEqual(n2, 0)
956 self.assertLessEqual(n2, n1)
957
958 def test_weak_keyed_len_race(self):
959 self.check_len_race(weakref.WeakKeyDictionary, lambda k: (k, 1))
960
961 def test_weak_valued_len_race(self):
962 self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k))
963
Fred Drakeb0fefc52001-03-23 04:22:45 +0000964 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000965 #
966 # This exercises d.copy(), d.items(), d[], del d[], len(d).
967 #
968 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000969 for o in objects:
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000970 self.assertEqual(weakref.getweakrefcount(o), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000971 self.assertTrue(o is dict[o.arg],
Fred Drakeb0fefc52001-03-23 04:22:45 +0000972 "wrong object returned by weak dict!")
Barry Warsawecaab832008-09-04 01:42:51 +0000973 items1 = list(dict.items())
974 items2 = list(dict.copy().items())
Fred Drakeb0fefc52001-03-23 04:22:45 +0000975 items1.sort()
976 items2.sort()
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000977 self.assertEqual(items1, items2,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000978 "cloning of weak-valued dictionary did not work!")
979 del items1, items2
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000980 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000981 del objects[0]
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000982 self.assertEqual(len(dict), self.COUNT - 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000983 "deleting object did not cause dictionary update")
984 del objects, o
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000985 self.assertEqual(len(dict), 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +0000986 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000987 # regression on SF bug #447152:
988 dict = weakref.WeakValueDictionary()
989 self.assertRaises(KeyError, dict.__getitem__, 1)
990 dict[2] = C()
991 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000992
993 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000994 #
995 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000996 # len(d), k in d.
Fred Drake0e540c32001-05-02 05:44:22 +0000997 #
998 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000999 for o in objects:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001000 self.assertTrue(weakref.getweakrefcount(o) == 1,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001001 "wrong number of weak references to %r!" % o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001002 self.assertTrue(o.arg is dict[o],
Fred Drakeb0fefc52001-03-23 04:22:45 +00001003 "wrong object returned by weak dict!")
1004 items1 = dict.items()
1005 items2 = dict.copy().items()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001006 self.assertEqual(set(items1), set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001007 "cloning of weak-keyed dictionary did not work!")
1008 del items1, items2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001009 self.assertEqual(len(dict), self.COUNT)
Fred Drakeb0fefc52001-03-23 04:22:45 +00001010 del objects[0]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001011 self.assertTrue(len(dict) == (self.COUNT - 1),
Fred Drakeb0fefc52001-03-23 04:22:45 +00001012 "deleting object did not cause dictionary update")
1013 del objects, o
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001014 self.assertTrue(len(dict) == 0,
Fred Drakeb0fefc52001-03-23 04:22:45 +00001015 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +00001016 o = Object(42)
1017 dict[o] = "What is the meaning of the universe?"
Benjamin Peterson577473f2010-01-19 00:09:57 +00001018 self.assertIn(o, dict)
1019 self.assertNotIn(34, dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +00001020
Fred Drake0e540c32001-05-02 05:44:22 +00001021 def test_weak_keyed_iters(self):
1022 dict, objects = self.make_weak_keyed_dict()
1023 self.check_iters(dict)
1024
Thomas Wouters477c8d52006-05-27 19:21:47 +00001025 # Test keyrefs()
1026 refs = dict.keyrefs()
1027 self.assertEqual(len(refs), len(objects))
1028 objects2 = list(objects)
1029 for wr in refs:
1030 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001031 self.assertIn(ob, dict)
1032 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001033 self.assertEqual(ob.arg, dict[ob])
1034 objects2.remove(ob)
1035 self.assertEqual(len(objects2), 0)
1036
1037 # Test iterkeyrefs()
1038 objects2 = list(objects)
Barry Warsawecaab832008-09-04 01:42:51 +00001039 self.assertEqual(len(list(dict.keyrefs())), len(objects))
1040 for wr in dict.keyrefs():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001041 ob = wr()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001042 self.assertIn(ob, dict)
1043 self.assertIn(ob, dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001044 self.assertEqual(ob.arg, dict[ob])
1045 objects2.remove(ob)
1046 self.assertEqual(len(objects2), 0)
1047
Fred Drake0e540c32001-05-02 05:44:22 +00001048 def test_weak_valued_iters(self):
1049 dict, objects = self.make_weak_valued_dict()
1050 self.check_iters(dict)
1051
Thomas Wouters477c8d52006-05-27 19:21:47 +00001052 # Test valuerefs()
1053 refs = dict.valuerefs()
1054 self.assertEqual(len(refs), len(objects))
1055 objects2 = list(objects)
1056 for wr in refs:
1057 ob = wr()
1058 self.assertEqual(ob, dict[ob.arg])
1059 self.assertEqual(ob.arg, dict[ob.arg].arg)
1060 objects2.remove(ob)
1061 self.assertEqual(len(objects2), 0)
1062
1063 # Test itervaluerefs()
1064 objects2 = list(objects)
1065 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
1066 for wr in dict.itervaluerefs():
1067 ob = wr()
1068 self.assertEqual(ob, dict[ob.arg])
1069 self.assertEqual(ob.arg, dict[ob.arg].arg)
1070 objects2.remove(ob)
1071 self.assertEqual(len(objects2), 0)
1072
Fred Drake0e540c32001-05-02 05:44:22 +00001073 def check_iters(self, dict):
1074 # item iterator:
Barry Warsawecaab832008-09-04 01:42:51 +00001075 items = list(dict.items())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001076 for item in dict.items():
Fred Drake0e540c32001-05-02 05:44:22 +00001077 items.remove(item)
Barry Warsawecaab832008-09-04 01:42:51 +00001078 self.assertFalse(items, "items() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +00001079
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001080 # key iterator, via __iter__():
Guido van Rossum07f24362007-02-11 22:59:48 +00001081 keys = list(dict.keys())
Fred Drake0e540c32001-05-02 05:44:22 +00001082 for k in dict:
1083 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001084 self.assertFalse(keys, "__iter__() did not touch all keys")
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001085
1086 # key iterator, via iterkeys():
Guido van Rossum07f24362007-02-11 22:59:48 +00001087 keys = list(dict.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001088 for k in dict.keys():
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001089 keys.remove(k)
Barry Warsawecaab832008-09-04 01:42:51 +00001090 self.assertFalse(keys, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +00001091
1092 # value iterator:
Guido van Rossum07f24362007-02-11 22:59:48 +00001093 values = list(dict.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001094 for v in dict.values():
Fred Drake0e540c32001-05-02 05:44:22 +00001095 values.remove(v)
Barry Warsawecaab832008-09-04 01:42:51 +00001096 self.assertFalse(values,
Fred Drakef425b1e2003-07-14 21:37:17 +00001097 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +00001098
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001099 def check_weak_destroy_while_iterating(self, dict, objects, iter_name):
1100 n = len(dict)
1101 it = iter(getattr(dict, iter_name)())
1102 next(it) # Trigger internal iteration
1103 # Destroy an object
1104 del objects[-1]
1105 gc.collect() # just in case
1106 # We have removed either the first consumed object, or another one
1107 self.assertIn(len(list(it)), [len(objects), len(objects) - 1])
1108 del it
1109 # The removal has been committed
1110 self.assertEqual(len(dict), n - 1)
1111
1112 def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
1113 # Check that we can explicitly mutate the weak dict without
1114 # interfering with delayed removal.
1115 # `testcontext` should create an iterator, destroy one of the
1116 # weakref'ed objects and then return a new key/value pair corresponding
1117 # to the destroyed object.
1118 with testcontext() as (k, v):
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.__delitem__, 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 self.assertRaises(KeyError, dict.pop, k)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001125 self.assertNotIn(k, dict)
Antoine Pitrouc1baa602010-01-08 17:54:23 +00001126 with testcontext() as (k, v):
1127 dict[k] = v
1128 self.assertEqual(dict[k], v)
1129 ddict = copy.copy(dict)
1130 with testcontext() as (k, v):
1131 dict.update(ddict)
1132 self.assertEqual(dict, ddict)
1133 with testcontext() as (k, v):
1134 dict.clear()
1135 self.assertEqual(len(dict), 0)
1136
1137 def test_weak_keys_destroy_while_iterating(self):
1138 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1139 dict, objects = self.make_weak_keyed_dict()
1140 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1141 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1142 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1143 self.check_weak_destroy_while_iterating(dict, objects, 'keyrefs')
1144 dict, objects = self.make_weak_keyed_dict()
1145 @contextlib.contextmanager
1146 def testcontext():
1147 try:
1148 it = iter(dict.items())
1149 next(it)
1150 # Schedule a key/value for removal and recreate it
1151 v = objects.pop().arg
1152 gc.collect() # just in case
1153 yield Object(v), v
1154 finally:
1155 it = None # should commit all removals
1156 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
1157
1158 def test_weak_values_destroy_while_iterating(self):
1159 # Issue #7105: iterators shouldn't crash when a key is implicitly removed
1160 dict, objects = self.make_weak_valued_dict()
1161 self.check_weak_destroy_while_iterating(dict, objects, 'keys')
1162 self.check_weak_destroy_while_iterating(dict, objects, 'items')
1163 self.check_weak_destroy_while_iterating(dict, objects, 'values')
1164 self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
1165 self.check_weak_destroy_while_iterating(dict, objects, 'valuerefs')
1166 dict, objects = self.make_weak_valued_dict()
1167 @contextlib.contextmanager
1168 def testcontext():
1169 try:
1170 it = iter(dict.items())
1171 next(it)
1172 # Schedule a key/value for removal and recreate it
1173 k = objects.pop().arg
1174 gc.collect() # just in case
1175 yield k, Object(k)
1176 finally:
1177 it = None # should commit all removals
1178 self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
1179
Guido van Rossum009afb72002-06-10 20:00:52 +00001180 def test_make_weak_keyed_dict_from_dict(self):
1181 o = Object(3)
1182 dict = weakref.WeakKeyDictionary({o:364})
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001183 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001184
1185 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
1186 o = Object(3)
1187 dict = weakref.WeakKeyDictionary({o:364})
1188 dict2 = weakref.WeakKeyDictionary(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001189 self.assertEqual(dict[o], 364)
Guido van Rossum009afb72002-06-10 20:00:52 +00001190
Fred Drake0e540c32001-05-02 05:44:22 +00001191 def make_weak_keyed_dict(self):
1192 dict = weakref.WeakKeyDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001193 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001194 for o in objects:
1195 dict[o] = o.arg
1196 return dict, objects
1197
Antoine Pitrouc06de472009-05-30 21:04:26 +00001198 def test_make_weak_valued_dict_from_dict(self):
1199 o = Object(3)
1200 dict = weakref.WeakValueDictionary({364:o})
1201 self.assertEqual(dict[364], o)
1202
1203 def test_make_weak_valued_dict_from_weak_valued_dict(self):
1204 o = Object(3)
1205 dict = weakref.WeakValueDictionary({364:o})
1206 dict2 = weakref.WeakValueDictionary(dict)
1207 self.assertEqual(dict[364], o)
1208
Fred Drake0e540c32001-05-02 05:44:22 +00001209 def make_weak_valued_dict(self):
1210 dict = weakref.WeakValueDictionary()
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001211 objects = list(map(Object, range(self.COUNT)))
Fred Drake0e540c32001-05-02 05:44:22 +00001212 for o in objects:
1213 dict[o.arg] = o
1214 return dict, objects
1215
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001216 def check_popitem(self, klass, key1, value1, key2, value2):
1217 weakdict = klass()
1218 weakdict[key1] = value1
1219 weakdict[key2] = value2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001220 self.assertEqual(len(weakdict), 2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001221 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001222 self.assertEqual(len(weakdict), 1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001223 if k is key1:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001224 self.assertTrue(v is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001225 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001226 self.assertTrue(v is value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001227 k, v = weakdict.popitem()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001228 self.assertEqual(len(weakdict), 0)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001229 if k is key1:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001230 self.assertTrue(v is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001231 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001232 self.assertTrue(v is value2)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001233
1234 def test_weak_valued_dict_popitem(self):
1235 self.check_popitem(weakref.WeakValueDictionary,
1236 "key1", C(), "key2", C())
1237
1238 def test_weak_keyed_dict_popitem(self):
1239 self.check_popitem(weakref.WeakKeyDictionary,
1240 C(), "value 1", C(), "value 2")
1241
1242 def check_setdefault(self, klass, key, value1, value2):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001243 self.assertTrue(value1 is not value2,
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001244 "invalid test"
1245 " -- value parameters must be distinct objects")
1246 weakdict = klass()
1247 o = weakdict.setdefault(key, value1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001248 self.assertTrue(o is value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001249 self.assertIn(key, weakdict)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001250 self.assertTrue(weakdict.get(key) is value1)
1251 self.assertTrue(weakdict[key] is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001252
1253 o = weakdict.setdefault(key, value2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001254 self.assertTrue(o is value1)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001255 self.assertIn(key, weakdict)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001256 self.assertTrue(weakdict.get(key) is value1)
1257 self.assertTrue(weakdict[key] is value1)
Fred Drakeaaa48ff2001-05-10 17:16:38 +00001258
1259 def test_weak_valued_dict_setdefault(self):
1260 self.check_setdefault(weakref.WeakValueDictionary,
1261 "key", C(), C())
1262
1263 def test_weak_keyed_dict_setdefault(self):
1264 self.check_setdefault(weakref.WeakKeyDictionary,
1265 C(), "value 1", "value 2")
1266
Fred Drakea0a4ab12001-04-16 17:37:27 +00001267 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +00001268 #
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001269 # This exercises d.update(), len(d), d.keys(), k in d,
Fred Drake0e540c32001-05-02 05:44:22 +00001270 # d.get(), d[].
1271 #
Fred Drakea0a4ab12001-04-16 17:37:27 +00001272 weakdict = klass()
1273 weakdict.update(dict)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001274 self.assertEqual(len(weakdict), len(dict))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001275 for k in weakdict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001276 self.assertIn(k, dict, "mysterious new key appeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001277 v = dict.get(k)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001278 self.assertTrue(v is weakdict[k])
1279 self.assertTrue(v is weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001280 for k in dict.keys():
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001281 self.assertIn(k, weakdict, "original key disappeared in weak dict")
Fred Drakea0a4ab12001-04-16 17:37:27 +00001282 v = dict[k]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001283 self.assertTrue(v is weakdict[k])
1284 self.assertTrue(v is weakdict.get(k))
Fred Drakea0a4ab12001-04-16 17:37:27 +00001285
1286 def test_weak_valued_dict_update(self):
1287 self.check_update(weakref.WeakValueDictionary,
1288 {1: C(), 'a': C(), C(): C()})
1289
1290 def test_weak_keyed_dict_update(self):
1291 self.check_update(weakref.WeakKeyDictionary,
1292 {C(): 1, C(): 2, C(): 3})
1293
Fred Drakeccc75622001-09-06 14:52:39 +00001294 def test_weak_keyed_delitem(self):
1295 d = weakref.WeakKeyDictionary()
1296 o1 = Object('1')
1297 o2 = Object('2')
1298 d[o1] = 'something'
1299 d[o2] = 'something'
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001300 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001301 del d[o1]
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001302 self.assertEqual(len(d), 1)
Barry Warsawecaab832008-09-04 01:42:51 +00001303 self.assertEqual(list(d.keys()), [o2])
Fred Drakeccc75622001-09-06 14:52:39 +00001304
1305 def test_weak_valued_delitem(self):
1306 d = weakref.WeakValueDictionary()
1307 o1 = Object('1')
1308 o2 = Object('2')
1309 d['something'] = o1
1310 d['something else'] = o2
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001311 self.assertEqual(len(d), 2)
Fred Drakeccc75622001-09-06 14:52:39 +00001312 del d['something']
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001313 self.assertEqual(len(d), 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001314 self.assertTrue(list(d.items()) == [('something else', o2)])
Fred Drakeccc75622001-09-06 14:52:39 +00001315
Tim Peters886128f2003-05-25 01:45:11 +00001316 def test_weak_keyed_bad_delitem(self):
1317 d = weakref.WeakKeyDictionary()
1318 o = Object('1')
1319 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +00001320 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +00001321 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +00001322 self.assertRaises(KeyError, d.__getitem__, o)
1323
1324 # If a key isn't of a weakly referencable type, __getitem__ and
1325 # __setitem__ raise TypeError. __delitem__ should too.
1326 self.assertRaises(TypeError, d.__delitem__, 13)
1327 self.assertRaises(TypeError, d.__getitem__, 13)
1328 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001329
1330 def test_weak_keyed_cascading_deletes(self):
1331 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1332 # over the keys via self.data.iterkeys(). If things vanished from
1333 # the dict during this (or got added), that caused a RuntimeError.
1334
1335 d = weakref.WeakKeyDictionary()
1336 mutate = False
1337
1338 class C(object):
1339 def __init__(self, i):
1340 self.value = i
1341 def __hash__(self):
1342 return hash(self.value)
1343 def __eq__(self, other):
1344 if mutate:
1345 # Side effect that mutates the dict, by removing the
1346 # last strong reference to a key.
1347 del objs[-1]
1348 return self.value == other.value
1349
1350 objs = [C(i) for i in range(4)]
1351 for o in objs:
1352 d[o] = o.value
1353 del o # now the only strong references to keys are in objs
1354 # Find the order in which iterkeys sees the keys.
Barry Warsawecaab832008-09-04 01:42:51 +00001355 objs = list(d.keys())
Tim Peters886128f2003-05-25 01:45:11 +00001356 # Reverse it, so that the iteration implementation of __delitem__
1357 # has to keep looping to find the first object we delete.
1358 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001359
Tim Peters886128f2003-05-25 01:45:11 +00001360 # Turn on mutation in C.__eq__. The first time thru the loop,
1361 # under the iterkeys() business the first comparison will delete
1362 # the last item iterkeys() would see, and that causes a
1363 # RuntimeError: dictionary changed size during iteration
1364 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001365 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001366 # "for o in obj" loop would have gotten to.
1367 mutate = True
1368 count = 0
1369 for o in objs:
1370 count += 1
1371 del d[o]
1372 self.assertEqual(len(d), 0)
1373 self.assertEqual(count, 2)
1374
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001375from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001376
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001377class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001378 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001379 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001380 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001381 def _reference(self):
1382 return self.__ref.copy()
1383
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001384class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001385 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001386 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001387 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001388 def _reference(self):
1389 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001390
Georg Brandlb533e262008-05-25 18:19:30 +00001391libreftest = """ Doctest for examples in the library reference: weakref.rst
Georg Brandl9a65d582005-07-02 19:07:30 +00001392
1393>>> import weakref
1394>>> class Dict(dict):
1395... pass
1396...
1397>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1398>>> r = weakref.ref(obj)
Guido van Rossum7131f842007-02-09 20:13:25 +00001399>>> print(r() is obj)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001400True
Georg Brandl9a65d582005-07-02 19:07:30 +00001401
1402>>> import weakref
1403>>> class Object:
1404... pass
1405...
1406>>> o = Object()
1407>>> r = weakref.ref(o)
1408>>> o2 = r()
1409>>> o is o2
1410True
1411>>> del o, o2
Guido van Rossum7131f842007-02-09 20:13:25 +00001412>>> print(r())
Georg Brandl9a65d582005-07-02 19:07:30 +00001413None
1414
1415>>> import weakref
1416>>> class ExtendedRef(weakref.ref):
1417... def __init__(self, ob, callback=None, **annotations):
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001418... super().__init__(ob, callback)
Georg Brandl9a65d582005-07-02 19:07:30 +00001419... self.__counter = 0
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001420... for k, v in annotations.items():
Georg Brandl9a65d582005-07-02 19:07:30 +00001421... setattr(self, k, v)
1422... def __call__(self):
1423... '''Return a pair containing the referent and the number of
1424... times the reference has been called.
1425... '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001426... ob = super().__call__()
Georg Brandl9a65d582005-07-02 19:07:30 +00001427... if ob is not None:
1428... self.__counter += 1
1429... ob = (ob, self.__counter)
1430... return ob
Guido van Rossumd8faa362007-04-27 19:54:29 +00001431...
Georg Brandl9a65d582005-07-02 19:07:30 +00001432>>> class A: # not in docs from here, just testing the ExtendedRef
1433... pass
1434...
1435>>> a = A()
1436>>> r = ExtendedRef(a, foo=1, bar="baz")
1437>>> r.foo
14381
1439>>> r.bar
1440'baz'
1441>>> r()[1]
14421
1443>>> r()[1]
14442
1445>>> r()[0] is a
1446True
1447
1448
1449>>> import weakref
1450>>> _id2obj_dict = weakref.WeakValueDictionary()
1451>>> def remember(obj):
1452... oid = id(obj)
1453... _id2obj_dict[oid] = obj
1454... return oid
1455...
1456>>> def id2obj(oid):
1457... return _id2obj_dict[oid]
1458...
1459>>> a = A() # from here, just testing
1460>>> a_id = remember(a)
1461>>> id2obj(a_id) is a
1462True
1463>>> del a
1464>>> try:
1465... id2obj(a_id)
1466... except KeyError:
Guido van Rossum7131f842007-02-09 20:13:25 +00001467... print('OK')
Georg Brandl9a65d582005-07-02 19:07:30 +00001468... else:
Guido van Rossum7131f842007-02-09 20:13:25 +00001469... print('WeakValueDictionary error')
Georg Brandl9a65d582005-07-02 19:07:30 +00001470OK
1471
1472"""
1473
1474__test__ = {'libreftest' : libreftest}
1475
Fred Drake2e2be372001-09-20 21:33:42 +00001476def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001477 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +00001478 ReferencesTestCase,
1479 MappingTestCase,
1480 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001481 WeakKeyDictionaryTestCase,
Amaury Forgeot d'Arcc856c7a2008-06-16 19:50:09 +00001482 SubclassableWeakrefTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001483 )
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001484 support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001485
1486
1487if __name__ == "__main__":
1488 test_main()