blob: 99a5178a6bdec95aacb4319928001b4cae3462da [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
Fred Drake5935ff02001-12-19 16:54:23 +00004import UserList
Fred Drake41deb1e2001-02-01 05:27:45 +00005import weakref
6
Barry Warsaw04f357c2002-07-23 19:04:11 +00007from test import test_support
Fred Drake41deb1e2001-02-01 05:27:45 +00008
Thomas Woutersb2137042007-02-01 18:02:27 +00009# Used in ReferencesTestCase.test_ref_created_during_del() .
10ref_from_del = None
Fred Drake41deb1e2001-02-01 05:27:45 +000011
12class C:
Fred Drakeb0fefc52001-03-23 04:22:45 +000013 def method(self):
14 pass
Fred Drake41deb1e2001-02-01 05:27:45 +000015
16
Fred Drakeb0fefc52001-03-23 04:22:45 +000017class Callable:
18 bar = None
Fred Drake41deb1e2001-02-01 05:27:45 +000019
Fred Drakeb0fefc52001-03-23 04:22:45 +000020 def __call__(self, x):
21 self.bar = x
Fred Drake41deb1e2001-02-01 05:27:45 +000022
23
Fred Drakeb0fefc52001-03-23 04:22:45 +000024def create_function():
25 def f(): pass
26 return f
27
28def create_bound_method():
29 return C().method
30
31def create_unbound_method():
32 return C.method
Fred Drake41deb1e2001-02-01 05:27:45 +000033
34
Fred Drakeb0fefc52001-03-23 04:22:45 +000035class TestBase(unittest.TestCase):
36
37 def setUp(self):
38 self.cbcalled = 0
39
40 def callback(self, ref):
41 self.cbcalled += 1
Fred Drake41deb1e2001-02-01 05:27:45 +000042
43
Fred Drakeb0fefc52001-03-23 04:22:45 +000044class ReferencesTestCase(TestBase):
Fred Drake41deb1e2001-02-01 05:27:45 +000045
Fred Drakeb0fefc52001-03-23 04:22:45 +000046 def test_basic_ref(self):
47 self.check_basic_ref(C)
48 self.check_basic_ref(create_function)
49 self.check_basic_ref(create_bound_method)
50 self.check_basic_ref(create_unbound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000051
Fred Drake43735da2002-04-11 03:59:42 +000052 # Just make sure the tp_repr handler doesn't raise an exception.
53 # Live reference:
54 o = C()
55 wr = weakref.ref(o)
Brett Cannon0b70cca2006-08-25 02:59:59 +000056 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000057 # Dead reference:
58 del o
Brett Cannon0b70cca2006-08-25 02:59:59 +000059 repr(wr)
Fred Drake43735da2002-04-11 03:59:42 +000060
Fred Drakeb0fefc52001-03-23 04:22:45 +000061 def test_basic_callback(self):
62 self.check_basic_callback(C)
63 self.check_basic_callback(create_function)
64 self.check_basic_callback(create_bound_method)
65 self.check_basic_callback(create_unbound_method)
Fred Drake41deb1e2001-02-01 05:27:45 +000066
Fred Drakeb0fefc52001-03-23 04:22:45 +000067 def test_multiple_callbacks(self):
68 o = C()
69 ref1 = weakref.ref(o, self.callback)
70 ref2 = weakref.ref(o, self.callback)
71 del o
72 self.assert_(ref1() is None,
73 "expected reference to be invalidated")
74 self.assert_(ref2() is None,
75 "expected reference to be invalidated")
76 self.assert_(self.cbcalled == 2,
77 "callback not called the right number of times")
Fred Drake41deb1e2001-02-01 05:27:45 +000078
Fred Drake705088e2001-04-13 17:18:15 +000079 def test_multiple_selfref_callbacks(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +000080 # Make sure all references are invalidated before callbacks are called
Fred Drake705088e2001-04-13 17:18:15 +000081 #
82 # What's important here is that we're using the first
83 # reference in the callback invoked on the second reference
84 # (the most recently created ref is cleaned up first). This
85 # tests that all references to the object are invalidated
86 # before any of the callbacks are invoked, so that we only
87 # have one invocation of _weakref.c:cleanup_helper() active
88 # for a particular object at a time.
89 #
90 def callback(object, self=self):
91 self.ref()
92 c = C()
93 self.ref = weakref.ref(c, callback)
94 ref1 = weakref.ref(c, callback)
95 del c
96
Fred Drakeb0fefc52001-03-23 04:22:45 +000097 def test_proxy_ref(self):
98 o = C()
99 o.bar = 1
100 ref1 = weakref.proxy(o, self.callback)
101 ref2 = weakref.proxy(o, self.callback)
102 del o
Fred Drake41deb1e2001-02-01 05:27:45 +0000103
Fred Drakeb0fefc52001-03-23 04:22:45 +0000104 def check(proxy):
105 proxy.bar
Fred Drake41deb1e2001-02-01 05:27:45 +0000106
Neal Norwitz2633c692007-02-26 22:22:47 +0000107 self.assertRaises(ReferenceError, check, ref1)
108 self.assertRaises(ReferenceError, check, ref2)
109 self.assertRaises(ReferenceError, bool, weakref.proxy(C()))
Fred Drakeb0fefc52001-03-23 04:22:45 +0000110 self.assert_(self.cbcalled == 2)
Fred Drake41deb1e2001-02-01 05:27:45 +0000111
Fred Drakeb0fefc52001-03-23 04:22:45 +0000112 def check_basic_ref(self, factory):
113 o = factory()
114 ref = weakref.ref(o)
115 self.assert_(ref() is not None,
116 "weak reference to live object should be live")
117 o2 = ref()
118 self.assert_(o is o2,
119 "<ref>() should return original object if live")
Fred Drake41deb1e2001-02-01 05:27:45 +0000120
Fred Drakeb0fefc52001-03-23 04:22:45 +0000121 def check_basic_callback(self, factory):
122 self.cbcalled = 0
123 o = factory()
124 ref = weakref.ref(o, self.callback)
125 del o
Fred Drake705088e2001-04-13 17:18:15 +0000126 self.assert_(self.cbcalled == 1,
127 "callback did not properly set 'cbcalled'")
128 self.assert_(ref() is None,
129 "ref2 should be dead after deleting object reference")
Fred Drake41deb1e2001-02-01 05:27:45 +0000130
Fred Drakeb0fefc52001-03-23 04:22:45 +0000131 def test_ref_reuse(self):
132 o = C()
133 ref1 = weakref.ref(o)
134 # create a proxy to make sure that there's an intervening creation
135 # between these two; it should make no difference
136 proxy = weakref.proxy(o)
137 ref2 = weakref.ref(o)
138 self.assert_(ref1 is ref2,
139 "reference object w/out callback should be re-used")
Fred Drake41deb1e2001-02-01 05:27:45 +0000140
Fred Drakeb0fefc52001-03-23 04:22:45 +0000141 o = C()
142 proxy = weakref.proxy(o)
143 ref1 = weakref.ref(o)
144 ref2 = weakref.ref(o)
145 self.assert_(ref1 is ref2,
146 "reference object w/out callback should be re-used")
147 self.assert_(weakref.getweakrefcount(o) == 2,
148 "wrong weak ref count for object")
149 del proxy
150 self.assert_(weakref.getweakrefcount(o) == 1,
151 "wrong weak ref count for object after deleting proxy")
Fred Drake41deb1e2001-02-01 05:27:45 +0000152
Fred Drakeb0fefc52001-03-23 04:22:45 +0000153 def test_proxy_reuse(self):
154 o = C()
155 proxy1 = weakref.proxy(o)
156 ref = weakref.ref(o)
157 proxy2 = weakref.proxy(o)
158 self.assert_(proxy1 is proxy2,
159 "proxy object w/out callback should have been re-used")
160
161 def test_basic_proxy(self):
162 o = C()
163 self.check_proxy(o, weakref.proxy(o))
164
Fred Drake5935ff02001-12-19 16:54:23 +0000165 L = UserList.UserList()
166 p = weakref.proxy(L)
167 self.failIf(p, "proxy for empty UserList should be false")
168 p.append(12)
169 self.assertEqual(len(L), 1)
170 self.failUnless(p, "proxy for non-empty UserList should be true")
171 p[:] = [2, 3]
172 self.assertEqual(len(L), 2)
173 self.assertEqual(len(p), 2)
Fred Drakef425b1e2003-07-14 21:37:17 +0000174 self.failUnless(3 in p,
175 "proxy didn't support __contains__() properly")
Fred Drake5935ff02001-12-19 16:54:23 +0000176 p[1] = 5
177 self.assertEqual(L[1], 5)
178 self.assertEqual(p[1], 5)
179 L2 = UserList.UserList(L)
180 p2 = weakref.proxy(L2)
181 self.assertEqual(p, p2)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000182 ## self.assertEqual(repr(L2), repr(p2))
Fred Drake43735da2002-04-11 03:59:42 +0000183 L3 = UserList.UserList(range(10))
184 p3 = weakref.proxy(L3)
185 self.assertEqual(L3[:], p3[:])
186 self.assertEqual(L3[5:], p3[5:])
187 self.assertEqual(L3[:5], p3[:5])
188 self.assertEqual(L3[2:5], p3[2:5])
Fred Drake5935ff02001-12-19 16:54:23 +0000189
Fred Drakeea2adc92004-02-03 19:56:46 +0000190 # The PyWeakref_* C API is documented as allowing either NULL or
191 # None as the value for the callback, where either means "no
192 # callback". The "no callback" ref and proxy objects are supposed
193 # to be shared so long as they exist by all callers so long as
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000194 # they are active. In Python 2.3.3 and earlier, this guarantee
Fred Drakeea2adc92004-02-03 19:56:46 +0000195 # was not honored, and was broken in different ways for
196 # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
197
198 def test_shared_ref_without_callback(self):
199 self.check_shared_without_callback(weakref.ref)
200
201 def test_shared_proxy_without_callback(self):
202 self.check_shared_without_callback(weakref.proxy)
203
204 def check_shared_without_callback(self, makeref):
205 o = Object(1)
206 p1 = makeref(o, None)
207 p2 = makeref(o, None)
208 self.assert_(p1 is p2, "both callbacks were None in the C API")
209 del p1, p2
210 p1 = makeref(o)
211 p2 = makeref(o, None)
212 self.assert_(p1 is p2, "callbacks were NULL, None in the C API")
213 del p1, p2
214 p1 = makeref(o)
215 p2 = makeref(o)
216 self.assert_(p1 is p2, "both callbacks were NULL in the C API")
217 del p1, p2
218 p1 = makeref(o, None)
219 p2 = makeref(o)
220 self.assert_(p1 is p2, "callbacks were None, NULL in the C API")
221
Fred Drakeb0fefc52001-03-23 04:22:45 +0000222 def test_callable_proxy(self):
223 o = Callable()
224 ref1 = weakref.proxy(o)
225
226 self.check_proxy(o, ref1)
227
228 self.assert_(type(ref1) is weakref.CallableProxyType,
229 "proxy is not of callable type")
230 ref1('twinkies!')
231 self.assert_(o.bar == 'twinkies!',
232 "call through proxy not passed through to original")
Fred Drake3bb4d212001-10-18 19:28:29 +0000233 ref1(x='Splat.')
234 self.assert_(o.bar == 'Splat.',
235 "call through proxy not passed through to original")
Fred Drakeb0fefc52001-03-23 04:22:45 +0000236
237 # expect due to too few args
238 self.assertRaises(TypeError, ref1)
239
240 # expect due to too many args
241 self.assertRaises(TypeError, ref1, 1, 2, 3)
242
243 def check_proxy(self, o, proxy):
244 o.foo = 1
245 self.assert_(proxy.foo == 1,
246 "proxy does not reflect attribute addition")
247 o.foo = 2
248 self.assert_(proxy.foo == 2,
249 "proxy does not reflect attribute modification")
250 del o.foo
251 self.assert_(not hasattr(proxy, 'foo'),
252 "proxy does not reflect attribute removal")
253
254 proxy.foo = 1
255 self.assert_(o.foo == 1,
256 "object does not reflect attribute addition via proxy")
257 proxy.foo = 2
258 self.assert_(
259 o.foo == 2,
260 "object does not reflect attribute modification via proxy")
261 del proxy.foo
262 self.assert_(not hasattr(o, 'foo'),
263 "object does not reflect attribute removal via proxy")
264
Raymond Hettingerd693a812003-06-30 04:18:48 +0000265 def test_proxy_deletion(self):
266 # Test clearing of SF bug #762891
267 class Foo:
268 result = None
269 def __delitem__(self, accessor):
270 self.result = accessor
271 g = Foo()
272 f = weakref.proxy(g)
273 del f[0]
274 self.assertEqual(f.result, 0)
275
Raymond Hettingere6c470f2005-03-27 03:04:54 +0000276 def test_proxy_bool(self):
277 # Test clearing of SF bug #1170766
278 class List(list): pass
279 lyst = List()
280 self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
281
Fred Drakeb0fefc52001-03-23 04:22:45 +0000282 def test_getweakrefcount(self):
283 o = C()
284 ref1 = weakref.ref(o)
285 ref2 = weakref.ref(o, self.callback)
286 self.assert_(weakref.getweakrefcount(o) == 2,
287 "got wrong number of weak reference objects")
288
289 proxy1 = weakref.proxy(o)
290 proxy2 = weakref.proxy(o, self.callback)
291 self.assert_(weakref.getweakrefcount(o) == 4,
292 "got wrong number of weak reference objects")
293
Fred Drakeea2adc92004-02-03 19:56:46 +0000294 del ref1, ref2, proxy1, proxy2
295 self.assert_(weakref.getweakrefcount(o) == 0,
296 "weak reference objects not unlinked from"
297 " referent when discarded.")
298
Walter Dörwaldb167b042003-12-11 12:34:05 +0000299 # assumes ints do not support weakrefs
300 self.assert_(weakref.getweakrefcount(1) == 0,
301 "got wrong number of weak reference objects for int")
302
Fred Drakeb0fefc52001-03-23 04:22:45 +0000303 def test_getweakrefs(self):
304 o = C()
305 ref1 = weakref.ref(o, self.callback)
306 ref2 = weakref.ref(o, self.callback)
307 del ref1
308 self.assert_(weakref.getweakrefs(o) == [ref2],
309 "list of refs does not match")
310
311 o = C()
312 ref1 = weakref.ref(o, self.callback)
313 ref2 = weakref.ref(o, self.callback)
314 del ref2
315 self.assert_(weakref.getweakrefs(o) == [ref1],
316 "list of refs does not match")
317
Fred Drakeea2adc92004-02-03 19:56:46 +0000318 del ref1
319 self.assert_(weakref.getweakrefs(o) == [],
320 "list of refs not cleared")
321
Walter Dörwaldb167b042003-12-11 12:34:05 +0000322 # assumes ints do not support weakrefs
323 self.assert_(weakref.getweakrefs(1) == [],
324 "list of refs does not match for int")
325
Fred Drake39c27f12001-10-18 18:06:05 +0000326 def test_newstyle_number_ops(self):
327 class F(float):
328 pass
329 f = F(2.0)
330 p = weakref.proxy(f)
331 self.assert_(p + 1.0 == 3.0)
332 self.assert_(1.0 + p == 3.0) # this used to SEGV
333
Fred Drake2a64f462001-12-10 23:46:02 +0000334 def test_callbacks_protected(self):
Guido van Rossum9eee5542002-08-22 20:21:30 +0000335 # Callbacks protected from already-set exceptions?
Fred Drake2a64f462001-12-10 23:46:02 +0000336 # Regression test for SF bug #478534.
337 class BogusError(Exception):
338 pass
339 data = {}
340 def remove(k):
341 del data[k]
342 def encapsulate():
343 f = lambda : ()
344 data[weakref.ref(f, remove)] = None
345 raise BogusError
346 try:
347 encapsulate()
348 except BogusError:
349 pass
350 else:
351 self.fail("exception not properly restored")
352 try:
353 encapsulate()
354 except BogusError:
355 pass
356 else:
357 self.fail("exception not properly restored")
358
Tim Petersadd09b42003-11-12 20:43:28 +0000359 def test_sf_bug_840829(self):
360 # "weakref callbacks and gc corrupt memory"
361 # subtype_dealloc erroneously exposed a new-style instance
362 # already in the process of getting deallocated to gc,
363 # causing double-deallocation if the instance had a weakref
364 # callback that triggered gc.
365 # If the bug exists, there probably won't be an obvious symptom
366 # in a release build. In a debug build, a segfault will occur
367 # when the second attempt to remove the instance from the "list
368 # of all objects" occurs.
369
370 import gc
371
372 class C(object):
373 pass
374
375 c = C()
376 wr = weakref.ref(c, lambda ignore: gc.collect())
377 del c
378
Tim Petersf7f9e992003-11-13 21:59:32 +0000379 # There endeth the first part. It gets worse.
380 del wr
381
382 c1 = C()
383 c1.i = C()
384 wr = weakref.ref(c1.i, lambda ignore: gc.collect())
385
386 c2 = C()
387 c2.c1 = c1
388 del c1 # still alive because c2 points to it
389
390 # Now when subtype_dealloc gets called on c2, it's not enough just
391 # that c2 is immune from gc while the weakref callbacks associated
392 # with c2 execute (there are none in this 2nd half of the test, btw).
393 # subtype_dealloc goes on to call the base classes' deallocs too,
394 # so any gc triggered by weakref callbacks associated with anything
395 # torn down by a base class dealloc can also trigger double
396 # deallocation of c2.
397 del c2
Fred Drake41deb1e2001-02-01 05:27:45 +0000398
Tim Peters403a2032003-11-20 21:21:46 +0000399 def test_callback_in_cycle_1(self):
400 import gc
401
402 class J(object):
403 pass
404
405 class II(object):
406 def acallback(self, ignore):
407 self.J
408
409 I = II()
410 I.J = J
411 I.wr = weakref.ref(J, I.acallback)
412
413 # Now J and II are each in a self-cycle (as all new-style class
414 # objects are, since their __mro__ points back to them). I holds
415 # both a weak reference (I.wr) and a strong reference (I.J) to class
416 # J. I is also in a cycle (I.wr points to a weakref that references
417 # I.acallback). When we del these three, they all become trash, but
418 # the cycles prevent any of them from getting cleaned up immediately.
419 # Instead they have to wait for cyclic gc to deduce that they're
420 # trash.
421 #
422 # gc used to call tp_clear on all of them, and the order in which
423 # it does that is pretty accidental. The exact order in which we
424 # built up these things manages to provoke gc into running tp_clear
425 # in just the right order (I last). Calling tp_clear on II leaves
426 # behind an insane class object (its __mro__ becomes NULL). Calling
427 # tp_clear on J breaks its self-cycle, but J doesn't get deleted
428 # just then because of the strong reference from I.J. Calling
429 # tp_clear on I starts to clear I's __dict__, and just happens to
430 # clear I.J first -- I.wr is still intact. That removes the last
431 # reference to J, which triggers the weakref callback. The callback
432 # tries to do "self.J", and instances of new-style classes look up
433 # attributes ("J") in the class dict first. The class (II) wants to
434 # search II.__mro__, but that's NULL. The result was a segfault in
435 # a release build, and an assert failure in a debug build.
436 del I, J, II
437 gc.collect()
438
439 def test_callback_in_cycle_2(self):
440 import gc
441
442 # This is just like test_callback_in_cycle_1, except that II is an
443 # old-style class. The symptom is different then: an instance of an
444 # old-style class looks in its own __dict__ first. 'J' happens to
445 # get cleared from I.__dict__ before 'wr', and 'J' was never in II's
446 # __dict__, so the attribute isn't found. The difference is that
447 # the old-style II doesn't have a NULL __mro__ (it doesn't have any
448 # __mro__), so no segfault occurs. Instead it got:
449 # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ...
450 # Exception exceptions.AttributeError:
451 # "II instance has no attribute 'J'" in <bound method II.acallback
452 # of <?.II instance at 0x00B9B4B8>> ignored
453
454 class J(object):
455 pass
456
457 class II:
458 def acallback(self, ignore):
459 self.J
460
461 I = II()
462 I.J = J
463 I.wr = weakref.ref(J, I.acallback)
464
465 del I, J, II
466 gc.collect()
467
468 def test_callback_in_cycle_3(self):
469 import gc
470
471 # This one broke the first patch that fixed the last two. In this
472 # case, the objects reachable from the callback aren't also reachable
473 # from the object (c1) *triggering* the callback: you can get to
474 # c1 from c2, but not vice-versa. The result was that c2's __dict__
475 # got tp_clear'ed by the time the c2.cb callback got invoked.
476
477 class C:
478 def cb(self, ignore):
479 self.me
480 self.c1
481 self.wr
482
483 c1, c2 = C(), C()
484
485 c2.me = c2
486 c2.c1 = c1
487 c2.wr = weakref.ref(c1, c2.cb)
488
489 del c1, c2
490 gc.collect()
491
492 def test_callback_in_cycle_4(self):
493 import gc
494
495 # Like test_callback_in_cycle_3, except c2 and c1 have different
496 # classes. c2's class (C) isn't reachable from c1 then, so protecting
497 # objects reachable from the dying object (c1) isn't enough to stop
498 # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
499 # The result was a segfault (C.__mro__ was NULL when the callback
500 # tried to look up self.me).
501
502 class C(object):
503 def cb(self, ignore):
504 self.me
505 self.c1
506 self.wr
507
508 class D:
509 pass
510
511 c1, c2 = D(), C()
512
513 c2.me = c2
514 c2.c1 = c1
515 c2.wr = weakref.ref(c1, c2.cb)
516
517 del c1, c2, C, D
518 gc.collect()
519
520 def test_callback_in_cycle_resurrection(self):
521 import gc
522
523 # Do something nasty in a weakref callback: resurrect objects
524 # from dead cycles. For this to be attempted, the weakref and
525 # its callback must also be part of the cyclic trash (else the
526 # objects reachable via the callback couldn't be in cyclic trash
527 # to begin with -- the callback would act like an external root).
528 # But gc clears trash weakrefs with callbacks early now, which
529 # disables the callbacks, so the callbacks shouldn't get called
530 # at all (and so nothing actually gets resurrected).
531
532 alist = []
533 class C(object):
534 def __init__(self, value):
535 self.attribute = value
536
537 def acallback(self, ignore):
538 alist.append(self.c)
539
540 c1, c2 = C(1), C(2)
541 c1.c = c2
542 c2.c = c1
543 c1.wr = weakref.ref(c2, c1.acallback)
544 c2.wr = weakref.ref(c1, c2.acallback)
545
546 def C_went_away(ignore):
547 alist.append("C went away")
548 wr = weakref.ref(C, C_went_away)
549
550 del c1, c2, C # make them all trash
551 self.assertEqual(alist, []) # del isn't enough to reclaim anything
552
553 gc.collect()
554 # c1.wr and c2.wr were part of the cyclic trash, so should have
555 # been cleared without their callbacks executing. OTOH, the weakref
556 # to C is bound to a function local (wr), and wasn't trash, so that
557 # callback should have been invoked when C went away.
558 self.assertEqual(alist, ["C went away"])
559 # The remaining weakref should be dead now (its callback ran).
560 self.assertEqual(wr(), None)
561
562 del alist[:]
563 gc.collect()
564 self.assertEqual(alist, [])
565
566 def test_callbacks_on_callback(self):
567 import gc
568
569 # Set up weakref callbacks *on* weakref callbacks.
570 alist = []
571 def safe_callback(ignore):
572 alist.append("safe_callback called")
573
574 class C(object):
575 def cb(self, ignore):
576 alist.append("cb called")
577
578 c, d = C(), C()
579 c.other = d
580 d.other = c
581 callback = c.cb
582 c.wr = weakref.ref(d, callback) # this won't trigger
583 d.wr = weakref.ref(callback, d.cb) # ditto
584 external_wr = weakref.ref(callback, safe_callback) # but this will
585 self.assert_(external_wr() is callback)
586
587 # The weakrefs attached to c and d should get cleared, so that
588 # C.cb is never called. But external_wr isn't part of the cyclic
589 # trash, and no cyclic trash is reachable from it, so safe_callback
590 # should get invoked when the bound method object callback (c.cb)
591 # -- which is itself a callback, and also part of the cyclic trash --
592 # gets reclaimed at the end of gc.
593
594 del callback, c, d, C
595 self.assertEqual(alist, []) # del isn't enough to clean up cycles
596 gc.collect()
597 self.assertEqual(alist, ["safe_callback called"])
598 self.assertEqual(external_wr(), None)
599
600 del alist[:]
601 gc.collect()
602 self.assertEqual(alist, [])
603
Fred Drakebc875f52004-02-04 23:14:14 +0000604 def test_gc_during_ref_creation(self):
605 self.check_gc_during_creation(weakref.ref)
606
607 def test_gc_during_proxy_creation(self):
608 self.check_gc_during_creation(weakref.proxy)
609
610 def check_gc_during_creation(self, makeref):
611 thresholds = gc.get_threshold()
612 gc.set_threshold(1, 1, 1)
613 gc.collect()
Fred Drake55cf4342004-02-13 19:21:57 +0000614 class A:
615 pass
Fred Drakebc875f52004-02-04 23:14:14 +0000616
617 def callback(*args):
618 pass
619
Fred Drake55cf4342004-02-13 19:21:57 +0000620 referenced = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000621
Fred Drake55cf4342004-02-13 19:21:57 +0000622 a = A()
Fred Drakebc875f52004-02-04 23:14:14 +0000623 a.a = a
624 a.wr = makeref(referenced)
625
626 try:
627 # now make sure the object and the ref get labeled as
628 # cyclic trash:
Fred Drake55cf4342004-02-13 19:21:57 +0000629 a = A()
630 weakref.ref(referenced, callback)
Fred Drakebc875f52004-02-04 23:14:14 +0000631
632 finally:
633 gc.set_threshold(*thresholds)
634
Thomas Woutersb2137042007-02-01 18:02:27 +0000635 def test_ref_created_during_del(self):
636 # Bug #1377858
637 # A weakref created in an object's __del__() would crash the
638 # interpreter when the weakref was cleaned up since it would refer to
639 # non-existent memory. This test should not segfault the interpreter.
640 class Target(object):
641 def __del__(self):
642 global ref_from_del
643 ref_from_del = weakref.ref(self)
644
645 w = Target()
646
Fred Drake0a4dd392004-07-02 18:57:45 +0000647
648class SubclassableWeakrefTestCase(unittest.TestCase):
649
650 def test_subclass_refs(self):
651 class MyRef(weakref.ref):
652 def __init__(self, ob, callback=None, value=42):
653 self.value = value
654 super(MyRef, self).__init__(ob, callback)
655 def __call__(self):
656 self.called = True
657 return super(MyRef, self).__call__()
658 o = Object("foo")
659 mr = MyRef(o, value=24)
660 self.assert_(mr() is o)
661 self.assert_(mr.called)
662 self.assertEqual(mr.value, 24)
663 del o
664 self.assert_(mr() is None)
665 self.assert_(mr.called)
666
667 def test_subclass_refs_dont_replace_standard_refs(self):
668 class MyRef(weakref.ref):
669 pass
670 o = Object(42)
671 r1 = MyRef(o)
672 r2 = weakref.ref(o)
673 self.assert_(r1 is not r2)
674 self.assertEqual(weakref.getweakrefs(o), [r2, r1])
675 self.assertEqual(weakref.getweakrefcount(o), 2)
676 r3 = MyRef(o)
677 self.assertEqual(weakref.getweakrefcount(o), 3)
678 refs = weakref.getweakrefs(o)
679 self.assertEqual(len(refs), 3)
680 self.assert_(r2 is refs[0])
681 self.assert_(r1 in refs[1:])
682 self.assert_(r3 in refs[1:])
683
684 def test_subclass_refs_dont_conflate_callbacks(self):
685 class MyRef(weakref.ref):
686 pass
687 o = Object(42)
688 r1 = MyRef(o, id)
689 r2 = MyRef(o, str)
690 self.assert_(r1 is not r2)
691 refs = weakref.getweakrefs(o)
692 self.assert_(r1 in refs)
693 self.assert_(r2 in refs)
694
695 def test_subclass_refs_with_slots(self):
696 class MyRef(weakref.ref):
697 __slots__ = "slot1", "slot2"
698 def __new__(type, ob, callback, slot1, slot2):
699 return weakref.ref.__new__(type, ob, callback)
700 def __init__(self, ob, callback, slot1, slot2):
701 self.slot1 = slot1
702 self.slot2 = slot2
703 def meth(self):
704 return self.slot1 + self.slot2
705 o = Object(42)
706 r = MyRef(o, None, "abc", "def")
707 self.assertEqual(r.slot1, "abc")
708 self.assertEqual(r.slot2, "def")
709 self.assertEqual(r.meth(), "abcdef")
710 self.failIf(hasattr(r, "__dict__"))
711
712
Fred Drake41deb1e2001-02-01 05:27:45 +0000713class Object:
714 def __init__(self, arg):
715 self.arg = arg
716 def __repr__(self):
717 return "<Object %r>" % self.arg
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000718 def __lt__(self, other):
719 if isinstance(other, Object):
720 return self.arg < other.arg
721 return NotImplemented
722 def __hash__(self):
723 return hash(self.arg)
Fred Drake41deb1e2001-02-01 05:27:45 +0000724
Fred Drake41deb1e2001-02-01 05:27:45 +0000725
Fred Drakeb0fefc52001-03-23 04:22:45 +0000726class MappingTestCase(TestBase):
Martin v. Löwis5e163332001-02-27 18:36:56 +0000727
Fred Drakeb0fefc52001-03-23 04:22:45 +0000728 COUNT = 10
729
730 def test_weak_values(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000731 #
732 # This exercises d.copy(), d.items(), d[], del d[], len(d).
733 #
734 dict, objects = self.make_weak_valued_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000735 for o in objects:
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000736 self.assertEqual(weakref.getweakrefcount(o), 1)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000737 self.assert_(o is dict[o.arg],
738 "wrong object returned by weak dict!")
739 items1 = dict.items()
740 items2 = dict.copy().items()
741 items1.sort()
742 items2.sort()
743 self.assert_(items1 == items2,
744 "cloning of weak-valued dictionary did not work!")
745 del items1, items2
746 self.assert_(len(dict) == self.COUNT)
747 del objects[0]
748 self.assert_(len(dict) == (self.COUNT - 1),
749 "deleting object did not cause dictionary update")
750 del objects, o
751 self.assert_(len(dict) == 0,
752 "deleting the values did not clear the dictionary")
Fred Drake4fd06e02001-08-03 04:11:27 +0000753 # regression on SF bug #447152:
754 dict = weakref.WeakValueDictionary()
755 self.assertRaises(KeyError, dict.__getitem__, 1)
756 dict[2] = C()
757 self.assertRaises(KeyError, dict.__getitem__, 2)
Fred Drakeb0fefc52001-03-23 04:22:45 +0000758
759 def test_weak_keys(self):
Fred Drake0e540c32001-05-02 05:44:22 +0000760 #
761 # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000762 # len(d), k in d.
Fred Drake0e540c32001-05-02 05:44:22 +0000763 #
764 dict, objects = self.make_weak_keyed_dict()
Fred Drakeb0fefc52001-03-23 04:22:45 +0000765 for o in objects:
766 self.assert_(weakref.getweakrefcount(o) == 1,
767 "wrong number of weak references to %r!" % o)
768 self.assert_(o.arg is dict[o],
769 "wrong object returned by weak dict!")
770 items1 = dict.items()
771 items2 = dict.copy().items()
Raymond Hettingera690a992003-11-16 16:17:49 +0000772 self.assert_(set(items1) == set(items2),
Fred Drakeb0fefc52001-03-23 04:22:45 +0000773 "cloning of weak-keyed dictionary did not work!")
774 del items1, items2
775 self.assert_(len(dict) == self.COUNT)
776 del objects[0]
777 self.assert_(len(dict) == (self.COUNT - 1),
778 "deleting object did not cause dictionary update")
779 del objects, o
780 self.assert_(len(dict) == 0,
781 "deleting the keys did not clear the dictionary")
Fred Drake752eda42001-11-06 16:38:34 +0000782 o = Object(42)
783 dict[o] = "What is the meaning of the universe?"
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000784 self.assert_(o in dict)
785 self.assert_(34 not in dict)
Martin v. Löwis5e163332001-02-27 18:36:56 +0000786
Fred Drake0e540c32001-05-02 05:44:22 +0000787 def test_weak_keyed_iters(self):
788 dict, objects = self.make_weak_keyed_dict()
789 self.check_iters(dict)
790
Thomas Wouters477c8d52006-05-27 19:21:47 +0000791 # Test keyrefs()
792 refs = dict.keyrefs()
793 self.assertEqual(len(refs), len(objects))
794 objects2 = list(objects)
795 for wr in refs:
796 ob = wr()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000797 self.assert_(ob in dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000798 self.assert_(ob in dict)
799 self.assertEqual(ob.arg, dict[ob])
800 objects2.remove(ob)
801 self.assertEqual(len(objects2), 0)
802
803 # Test iterkeyrefs()
804 objects2 = list(objects)
805 self.assertEqual(len(list(dict.iterkeyrefs())), len(objects))
806 for wr in dict.iterkeyrefs():
807 ob = wr()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000808 self.assert_(ob in dict)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000809 self.assert_(ob in dict)
810 self.assertEqual(ob.arg, dict[ob])
811 objects2.remove(ob)
812 self.assertEqual(len(objects2), 0)
813
Fred Drake0e540c32001-05-02 05:44:22 +0000814 def test_weak_valued_iters(self):
815 dict, objects = self.make_weak_valued_dict()
816 self.check_iters(dict)
817
Thomas Wouters477c8d52006-05-27 19:21:47 +0000818 # Test valuerefs()
819 refs = dict.valuerefs()
820 self.assertEqual(len(refs), len(objects))
821 objects2 = list(objects)
822 for wr in refs:
823 ob = wr()
824 self.assertEqual(ob, dict[ob.arg])
825 self.assertEqual(ob.arg, dict[ob.arg].arg)
826 objects2.remove(ob)
827 self.assertEqual(len(objects2), 0)
828
829 # Test itervaluerefs()
830 objects2 = list(objects)
831 self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
832 for wr in dict.itervaluerefs():
833 ob = wr()
834 self.assertEqual(ob, dict[ob.arg])
835 self.assertEqual(ob.arg, dict[ob.arg].arg)
836 objects2.remove(ob)
837 self.assertEqual(len(objects2), 0)
838
Fred Drake0e540c32001-05-02 05:44:22 +0000839 def check_iters(self, dict):
840 # item iterator:
841 items = dict.items()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000842 for item in dict.items():
Fred Drake0e540c32001-05-02 05:44:22 +0000843 items.remove(item)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000844 self.assert_(len(items) == 0, "items() did not touch all items")
Fred Drake0e540c32001-05-02 05:44:22 +0000845
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000846 # key iterator, via __iter__():
Guido van Rossum07f24362007-02-11 22:59:48 +0000847 keys = list(dict.keys())
Fred Drake0e540c32001-05-02 05:44:22 +0000848 for k in dict:
849 keys.remove(k)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000850 self.assert_(len(keys) == 0, "__iter__() did not touch all keys")
851
852 # key iterator, via iterkeys():
Guido van Rossum07f24362007-02-11 22:59:48 +0000853 keys = list(dict.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000854 for k in dict.keys():
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000855 keys.remove(k)
856 self.assert_(len(keys) == 0, "iterkeys() did not touch all keys")
Fred Drake0e540c32001-05-02 05:44:22 +0000857
858 # value iterator:
Guido van Rossum07f24362007-02-11 22:59:48 +0000859 values = list(dict.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000860 for v in dict.values():
Fred Drake0e540c32001-05-02 05:44:22 +0000861 values.remove(v)
Fred Drakef425b1e2003-07-14 21:37:17 +0000862 self.assert_(len(values) == 0,
863 "itervalues() did not touch all values")
Fred Drake0e540c32001-05-02 05:44:22 +0000864
Guido van Rossum009afb72002-06-10 20:00:52 +0000865 def test_make_weak_keyed_dict_from_dict(self):
866 o = Object(3)
867 dict = weakref.WeakKeyDictionary({o:364})
868 self.assert_(dict[o] == 364)
869
870 def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
871 o = Object(3)
872 dict = weakref.WeakKeyDictionary({o:364})
873 dict2 = weakref.WeakKeyDictionary(dict)
874 self.assert_(dict[o] == 364)
875
Fred Drake0e540c32001-05-02 05:44:22 +0000876 def make_weak_keyed_dict(self):
877 dict = weakref.WeakKeyDictionary()
878 objects = map(Object, range(self.COUNT))
879 for o in objects:
880 dict[o] = o.arg
881 return dict, objects
882
883 def make_weak_valued_dict(self):
884 dict = weakref.WeakValueDictionary()
885 objects = map(Object, range(self.COUNT))
886 for o in objects:
887 dict[o.arg] = o
888 return dict, objects
889
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000890 def check_popitem(self, klass, key1, value1, key2, value2):
891 weakdict = klass()
892 weakdict[key1] = value1
893 weakdict[key2] = value2
894 self.assert_(len(weakdict) == 2)
895 k, v = weakdict.popitem()
896 self.assert_(len(weakdict) == 1)
897 if k is key1:
898 self.assert_(v is value1)
899 else:
900 self.assert_(v is value2)
901 k, v = weakdict.popitem()
902 self.assert_(len(weakdict) == 0)
903 if k is key1:
904 self.assert_(v is value1)
905 else:
906 self.assert_(v is value2)
907
908 def test_weak_valued_dict_popitem(self):
909 self.check_popitem(weakref.WeakValueDictionary,
910 "key1", C(), "key2", C())
911
912 def test_weak_keyed_dict_popitem(self):
913 self.check_popitem(weakref.WeakKeyDictionary,
914 C(), "value 1", C(), "value 2")
915
916 def check_setdefault(self, klass, key, value1, value2):
917 self.assert_(value1 is not value2,
918 "invalid test"
919 " -- value parameters must be distinct objects")
920 weakdict = klass()
921 o = weakdict.setdefault(key, value1)
922 self.assert_(o is value1)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000923 self.assert_(key in weakdict)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000924 self.assert_(weakdict.get(key) is value1)
925 self.assert_(weakdict[key] is value1)
926
927 o = weakdict.setdefault(key, value2)
928 self.assert_(o is value1)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000929 self.assert_(key in weakdict)
Fred Drakeaaa48ff2001-05-10 17:16:38 +0000930 self.assert_(weakdict.get(key) is value1)
931 self.assert_(weakdict[key] is value1)
932
933 def test_weak_valued_dict_setdefault(self):
934 self.check_setdefault(weakref.WeakValueDictionary,
935 "key", C(), C())
936
937 def test_weak_keyed_dict_setdefault(self):
938 self.check_setdefault(weakref.WeakKeyDictionary,
939 C(), "value 1", "value 2")
940
Fred Drakea0a4ab12001-04-16 17:37:27 +0000941 def check_update(self, klass, dict):
Fred Drake0e540c32001-05-02 05:44:22 +0000942 #
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000943 # This exercises d.update(), len(d), d.keys(), k in d,
Fred Drake0e540c32001-05-02 05:44:22 +0000944 # d.get(), d[].
945 #
Fred Drakea0a4ab12001-04-16 17:37:27 +0000946 weakdict = klass()
947 weakdict.update(dict)
948 self.assert_(len(weakdict) == len(dict))
949 for k in weakdict.keys():
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000950 self.assert_(k in dict,
Fred Drakea0a4ab12001-04-16 17:37:27 +0000951 "mysterious new key appeared in weak dict")
952 v = dict.get(k)
953 self.assert_(v is weakdict[k])
954 self.assert_(v is weakdict.get(k))
955 for k in dict.keys():
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000956 self.assert_(k in weakdict,
Fred Drakea0a4ab12001-04-16 17:37:27 +0000957 "original key disappeared in weak dict")
958 v = dict[k]
959 self.assert_(v is weakdict[k])
960 self.assert_(v is weakdict.get(k))
961
962 def test_weak_valued_dict_update(self):
963 self.check_update(weakref.WeakValueDictionary,
964 {1: C(), 'a': C(), C(): C()})
965
966 def test_weak_keyed_dict_update(self):
967 self.check_update(weakref.WeakKeyDictionary,
968 {C(): 1, C(): 2, C(): 3})
969
Fred Drakeccc75622001-09-06 14:52:39 +0000970 def test_weak_keyed_delitem(self):
971 d = weakref.WeakKeyDictionary()
972 o1 = Object('1')
973 o2 = Object('2')
974 d[o1] = 'something'
975 d[o2] = 'something'
976 self.assert_(len(d) == 2)
977 del d[o1]
978 self.assert_(len(d) == 1)
979 self.assert_(d.keys() == [o2])
980
981 def test_weak_valued_delitem(self):
982 d = weakref.WeakValueDictionary()
983 o1 = Object('1')
984 o2 = Object('2')
985 d['something'] = o1
986 d['something else'] = o2
987 self.assert_(len(d) == 2)
988 del d['something']
989 self.assert_(len(d) == 1)
990 self.assert_(d.items() == [('something else', o2)])
991
Tim Peters886128f2003-05-25 01:45:11 +0000992 def test_weak_keyed_bad_delitem(self):
993 d = weakref.WeakKeyDictionary()
994 o = Object('1')
995 # An attempt to delete an object that isn't there should raise
Tim Peters50d8b8b2003-05-25 17:44:31 +0000996 # KeyError. It didn't before 2.3.
Tim Peters886128f2003-05-25 01:45:11 +0000997 self.assertRaises(KeyError, d.__delitem__, o)
Tim Peters50d8b8b2003-05-25 17:44:31 +0000998 self.assertRaises(KeyError, d.__getitem__, o)
999
1000 # If a key isn't of a weakly referencable type, __getitem__ and
1001 # __setitem__ raise TypeError. __delitem__ should too.
1002 self.assertRaises(TypeError, d.__delitem__, 13)
1003 self.assertRaises(TypeError, d.__getitem__, 13)
1004 self.assertRaises(TypeError, d.__setitem__, 13, 13)
Tim Peters886128f2003-05-25 01:45:11 +00001005
1006 def test_weak_keyed_cascading_deletes(self):
1007 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1008 # over the keys via self.data.iterkeys(). If things vanished from
1009 # the dict during this (or got added), that caused a RuntimeError.
1010
1011 d = weakref.WeakKeyDictionary()
1012 mutate = False
1013
1014 class C(object):
1015 def __init__(self, i):
1016 self.value = i
1017 def __hash__(self):
1018 return hash(self.value)
1019 def __eq__(self, other):
1020 if mutate:
1021 # Side effect that mutates the dict, by removing the
1022 # last strong reference to a key.
1023 del objs[-1]
1024 return self.value == other.value
1025
1026 objs = [C(i) for i in range(4)]
1027 for o in objs:
1028 d[o] = o.value
1029 del o # now the only strong references to keys are in objs
1030 # Find the order in which iterkeys sees the keys.
1031 objs = d.keys()
1032 # Reverse it, so that the iteration implementation of __delitem__
1033 # has to keep looping to find the first object we delete.
1034 objs.reverse()
Tim Peters50d8b8b2003-05-25 17:44:31 +00001035
Tim Peters886128f2003-05-25 01:45:11 +00001036 # Turn on mutation in C.__eq__. The first time thru the loop,
1037 # under the iterkeys() business the first comparison will delete
1038 # the last item iterkeys() would see, and that causes a
1039 # RuntimeError: dictionary changed size during iteration
1040 # when the iterkeys() loop goes around to try comparing the next
Tim Peters50d8b8b2003-05-25 17:44:31 +00001041 # key. After this was fixed, it just deletes the last object *our*
Tim Peters886128f2003-05-25 01:45:11 +00001042 # "for o in obj" loop would have gotten to.
1043 mutate = True
1044 count = 0
1045 for o in objs:
1046 count += 1
1047 del d[o]
1048 self.assertEqual(len(d), 0)
1049 self.assertEqual(count, 2)
1050
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001051from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001052
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001053class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001054 """Check that WeakValueDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001055 __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
Walter Dörwald118f9312004-06-02 18:42:25 +00001056 type2test = weakref.WeakValueDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001057 def _reference(self):
1058 return self.__ref.copy()
1059
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +00001060class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
Fred Drakef425b1e2003-07-14 21:37:17 +00001061 """Check that WeakKeyDictionary conforms to the mapping protocol"""
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001062 __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
Walter Dörwald118f9312004-06-02 18:42:25 +00001063 type2test = weakref.WeakKeyDictionary
Raymond Hettinger2c2d3222003-03-09 07:05:43 +00001064 def _reference(self):
1065 return self.__ref.copy()
Martin v. Löwis5e163332001-02-27 18:36:56 +00001066
Georg Brandl9a65d582005-07-02 19:07:30 +00001067libreftest = """ Doctest for examples in the library reference: libweakref.tex
1068
1069>>> import weakref
1070>>> class Dict(dict):
1071... pass
1072...
1073>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
1074>>> r = weakref.ref(obj)
Guido van Rossum7131f842007-02-09 20:13:25 +00001075>>> print(r() is obj)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001076True
Georg Brandl9a65d582005-07-02 19:07:30 +00001077
1078>>> import weakref
1079>>> class Object:
1080... pass
1081...
1082>>> o = Object()
1083>>> r = weakref.ref(o)
1084>>> o2 = r()
1085>>> o is o2
1086True
1087>>> del o, o2
Guido van Rossum7131f842007-02-09 20:13:25 +00001088>>> print(r())
Georg Brandl9a65d582005-07-02 19:07:30 +00001089None
1090
1091>>> import weakref
1092>>> class ExtendedRef(weakref.ref):
1093... def __init__(self, ob, callback=None, **annotations):
1094... super(ExtendedRef, self).__init__(ob, callback)
1095... self.__counter = 0
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001096... for k, v in annotations.items():
Georg Brandl9a65d582005-07-02 19:07:30 +00001097... setattr(self, k, v)
1098... def __call__(self):
1099... '''Return a pair containing the referent and the number of
1100... times the reference has been called.
1101... '''
1102... ob = super(ExtendedRef, self).__call__()
1103... if ob is not None:
1104... self.__counter += 1
1105... ob = (ob, self.__counter)
1106... return ob
Guido van Rossumd8faa362007-04-27 19:54:29 +00001107...
Georg Brandl9a65d582005-07-02 19:07:30 +00001108>>> class A: # not in docs from here, just testing the ExtendedRef
1109... pass
1110...
1111>>> a = A()
1112>>> r = ExtendedRef(a, foo=1, bar="baz")
1113>>> r.foo
11141
1115>>> r.bar
1116'baz'
1117>>> r()[1]
11181
1119>>> r()[1]
11202
1121>>> r()[0] is a
1122True
1123
1124
1125>>> import weakref
1126>>> _id2obj_dict = weakref.WeakValueDictionary()
1127>>> def remember(obj):
1128... oid = id(obj)
1129... _id2obj_dict[oid] = obj
1130... return oid
1131...
1132>>> def id2obj(oid):
1133... return _id2obj_dict[oid]
1134...
1135>>> a = A() # from here, just testing
1136>>> a_id = remember(a)
1137>>> id2obj(a_id) is a
1138True
1139>>> del a
1140>>> try:
1141... id2obj(a_id)
1142... except KeyError:
Guido van Rossum7131f842007-02-09 20:13:25 +00001143... print('OK')
Georg Brandl9a65d582005-07-02 19:07:30 +00001144... else:
Guido van Rossum7131f842007-02-09 20:13:25 +00001145... print('WeakValueDictionary error')
Georg Brandl9a65d582005-07-02 19:07:30 +00001146OK
1147
1148"""
1149
1150__test__ = {'libreftest' : libreftest}
1151
Fred Drake2e2be372001-09-20 21:33:42 +00001152def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +00001153 test_support.run_unittest(
1154 ReferencesTestCase,
1155 MappingTestCase,
1156 WeakValueDictionaryTestCase,
Fred Drakef425b1e2003-07-14 21:37:17 +00001157 WeakKeyDictionaryTestCase,
1158 )
Georg Brandl9a65d582005-07-02 19:07:30 +00001159 test_support.run_doctest(sys.modules[__name__])
Fred Drake2e2be372001-09-20 21:33:42 +00001160
1161
1162if __name__ == "__main__":
1163 test_main()