Fred Drake | bc875f5 | 2004-02-04 23:14:14 +0000 | [diff] [blame] | 1 | import gc |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 2 | import sys |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 3 | import unittest |
Fred Drake | 5935ff0 | 2001-12-19 16:54:23 +0000 | [diff] [blame] | 4 | import UserList |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 5 | import weakref |
Georg Brandl | 88659b0 | 2008-05-20 08:40:43 +0000 | [diff] [blame] | 6 | import operator |
Kristján Valur Jónsson | 222b284 | 2013-12-05 10:03:45 +0000 | [diff] [blame] | 7 | import contextlib |
| 8 | import copy |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 9 | |
Barry Warsaw | 04f357c | 2002-07-23 19:04:11 +0000 | [diff] [blame] | 10 | from test import test_support |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 11 | |
Brett Cannon | f5bee30 | 2007-01-23 23:21:22 +0000 | [diff] [blame] | 12 | # Used in ReferencesTestCase.test_ref_created_during_del() . |
| 13 | ref_from_del = None |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 14 | |
| 15 | class C: |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 16 | def method(self): |
| 17 | pass |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 18 | |
| 19 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 20 | class Callable: |
| 21 | bar = None |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 22 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 23 | def __call__(self, x): |
| 24 | self.bar = x |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 25 | |
| 26 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 27 | def create_function(): |
| 28 | def f(): pass |
| 29 | return f |
| 30 | |
| 31 | def create_bound_method(): |
| 32 | return C().method |
| 33 | |
| 34 | def create_unbound_method(): |
| 35 | return C.method |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 36 | |
| 37 | |
Antoine Pitrou | b704eab | 2012-11-11 19:36:51 +0100 | [diff] [blame] | 38 | class Object: |
| 39 | def __init__(self, arg): |
| 40 | self.arg = arg |
| 41 | def __repr__(self): |
| 42 | return "<Object %r>" % self.arg |
| 43 | def __eq__(self, other): |
| 44 | if isinstance(other, Object): |
| 45 | return self.arg == other.arg |
| 46 | return NotImplemented |
| 47 | def __ne__(self, other): |
| 48 | if isinstance(other, Object): |
| 49 | return self.arg != other.arg |
| 50 | return NotImplemented |
| 51 | def __hash__(self): |
| 52 | return hash(self.arg) |
| 53 | |
| 54 | class RefCycle: |
| 55 | def __init__(self): |
| 56 | self.cycle = self |
| 57 | |
| 58 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 59 | class TestBase(unittest.TestCase): |
| 60 | |
| 61 | def setUp(self): |
| 62 | self.cbcalled = 0 |
| 63 | |
| 64 | def callback(self, ref): |
| 65 | self.cbcalled += 1 |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 66 | |
| 67 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 68 | class ReferencesTestCase(TestBase): |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 69 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 70 | def test_basic_ref(self): |
| 71 | self.check_basic_ref(C) |
| 72 | self.check_basic_ref(create_function) |
| 73 | self.check_basic_ref(create_bound_method) |
| 74 | self.check_basic_ref(create_unbound_method) |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 75 | |
Fred Drake | 43735da | 2002-04-11 03:59:42 +0000 | [diff] [blame] | 76 | # Just make sure the tp_repr handler doesn't raise an exception. |
| 77 | # Live reference: |
| 78 | o = C() |
| 79 | wr = weakref.ref(o) |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 80 | repr(wr) |
Fred Drake | 43735da | 2002-04-11 03:59:42 +0000 | [diff] [blame] | 81 | # Dead reference: |
| 82 | del o |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 83 | repr(wr) |
Fred Drake | 43735da | 2002-04-11 03:59:42 +0000 | [diff] [blame] | 84 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 85 | def test_basic_callback(self): |
| 86 | self.check_basic_callback(C) |
| 87 | self.check_basic_callback(create_function) |
| 88 | self.check_basic_callback(create_bound_method) |
| 89 | self.check_basic_callback(create_unbound_method) |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 90 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 91 | def test_multiple_callbacks(self): |
| 92 | o = C() |
| 93 | ref1 = weakref.ref(o, self.callback) |
| 94 | ref2 = weakref.ref(o, self.callback) |
| 95 | del o |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 96 | self.assertIsNone(ref1(), "expected reference to be invalidated") |
| 97 | self.assertIsNone(ref2(), "expected reference to be invalidated") |
| 98 | self.assertEqual(self.cbcalled, 2, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 99 | "callback not called the right number of times") |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 100 | |
Fred Drake | 705088e | 2001-04-13 17:18:15 +0000 | [diff] [blame] | 101 | def test_multiple_selfref_callbacks(self): |
Guido van Rossum | 9eee554 | 2002-08-22 20:21:30 +0000 | [diff] [blame] | 102 | # Make sure all references are invalidated before callbacks are called |
Fred Drake | 705088e | 2001-04-13 17:18:15 +0000 | [diff] [blame] | 103 | # |
| 104 | # What's important here is that we're using the first |
| 105 | # reference in the callback invoked on the second reference |
| 106 | # (the most recently created ref is cleaned up first). This |
| 107 | # tests that all references to the object are invalidated |
| 108 | # before any of the callbacks are invoked, so that we only |
| 109 | # have one invocation of _weakref.c:cleanup_helper() active |
| 110 | # for a particular object at a time. |
| 111 | # |
| 112 | def callback(object, self=self): |
| 113 | self.ref() |
| 114 | c = C() |
| 115 | self.ref = weakref.ref(c, callback) |
| 116 | ref1 = weakref.ref(c, callback) |
| 117 | del c |
| 118 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 119 | def test_proxy_ref(self): |
| 120 | o = C() |
| 121 | o.bar = 1 |
| 122 | ref1 = weakref.proxy(o, self.callback) |
| 123 | ref2 = weakref.proxy(o, self.callback) |
| 124 | del o |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 125 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 126 | def check(proxy): |
| 127 | proxy.bar |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 128 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 129 | self.assertRaises(weakref.ReferenceError, check, ref1) |
| 130 | self.assertRaises(weakref.ReferenceError, check, ref2) |
Neal Norwitz | bdcb941 | 2004-07-08 01:22:31 +0000 | [diff] [blame] | 131 | self.assertRaises(weakref.ReferenceError, bool, weakref.proxy(C())) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 132 | self.assertEqual(self.cbcalled, 2) |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 133 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 134 | def check_basic_ref(self, factory): |
| 135 | o = factory() |
| 136 | ref = weakref.ref(o) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 137 | self.assertIsNotNone(ref(), |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 138 | "weak reference to live object should be live") |
| 139 | o2 = ref() |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 140 | self.assertIs(o, o2, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 141 | "<ref>() should return original object if live") |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 142 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 143 | def check_basic_callback(self, factory): |
| 144 | self.cbcalled = 0 |
| 145 | o = factory() |
| 146 | ref = weakref.ref(o, self.callback) |
| 147 | del o |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 148 | self.assertEqual(self.cbcalled, 1, |
Fred Drake | 705088e | 2001-04-13 17:18:15 +0000 | [diff] [blame] | 149 | "callback did not properly set 'cbcalled'") |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 150 | self.assertIsNone(ref(), |
Fred Drake | 705088e | 2001-04-13 17:18:15 +0000 | [diff] [blame] | 151 | "ref2 should be dead after deleting object reference") |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 152 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 153 | def test_ref_reuse(self): |
| 154 | o = C() |
| 155 | ref1 = weakref.ref(o) |
| 156 | # create a proxy to make sure that there's an intervening creation |
| 157 | # between these two; it should make no difference |
| 158 | proxy = weakref.proxy(o) |
| 159 | ref2 = weakref.ref(o) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 160 | self.assertIs(ref1, ref2, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 161 | "reference object w/out callback should be re-used") |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 162 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 163 | o = C() |
| 164 | proxy = weakref.proxy(o) |
| 165 | ref1 = weakref.ref(o) |
| 166 | ref2 = weakref.ref(o) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 167 | self.assertIs(ref1, ref2, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 168 | "reference object w/out callback should be re-used") |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 169 | self.assertEqual(weakref.getweakrefcount(o), 2, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 170 | "wrong weak ref count for object") |
| 171 | del proxy |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 172 | self.assertEqual(weakref.getweakrefcount(o), 1, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 173 | "wrong weak ref count for object after deleting proxy") |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 174 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 175 | def test_proxy_reuse(self): |
| 176 | o = C() |
| 177 | proxy1 = weakref.proxy(o) |
| 178 | ref = weakref.ref(o) |
| 179 | proxy2 = weakref.proxy(o) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 180 | self.assertIs(proxy1, proxy2, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 181 | "proxy object w/out callback should have been re-used") |
| 182 | |
| 183 | def test_basic_proxy(self): |
| 184 | o = C() |
| 185 | self.check_proxy(o, weakref.proxy(o)) |
| 186 | |
Fred Drake | 5935ff0 | 2001-12-19 16:54:23 +0000 | [diff] [blame] | 187 | L = UserList.UserList() |
| 188 | p = weakref.proxy(L) |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 189 | self.assertFalse(p, "proxy for empty UserList should be false") |
Fred Drake | 5935ff0 | 2001-12-19 16:54:23 +0000 | [diff] [blame] | 190 | p.append(12) |
| 191 | self.assertEqual(len(L), 1) |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 192 | self.assertTrue(p, "proxy for non-empty UserList should be true") |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 193 | with test_support.check_py3k_warnings(): |
| 194 | p[:] = [2, 3] |
Fred Drake | 5935ff0 | 2001-12-19 16:54:23 +0000 | [diff] [blame] | 195 | self.assertEqual(len(L), 2) |
| 196 | self.assertEqual(len(p), 2) |
Ezio Melotti | aa98058 | 2010-01-23 23:04:36 +0000 | [diff] [blame] | 197 | self.assertIn(3, p, "proxy didn't support __contains__() properly") |
Fred Drake | 5935ff0 | 2001-12-19 16:54:23 +0000 | [diff] [blame] | 198 | p[1] = 5 |
| 199 | self.assertEqual(L[1], 5) |
| 200 | self.assertEqual(p[1], 5) |
| 201 | L2 = UserList.UserList(L) |
| 202 | p2 = weakref.proxy(L2) |
| 203 | self.assertEqual(p, p2) |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 204 | ## self.assertEqual(repr(L2), repr(p2)) |
Fred Drake | 43735da | 2002-04-11 03:59:42 +0000 | [diff] [blame] | 205 | L3 = UserList.UserList(range(10)) |
| 206 | p3 = weakref.proxy(L3) |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 207 | with test_support.check_py3k_warnings(): |
| 208 | self.assertEqual(L3[:], p3[:]) |
| 209 | self.assertEqual(L3[5:], p3[5:]) |
| 210 | self.assertEqual(L3[:5], p3[:5]) |
| 211 | self.assertEqual(L3[2:5], p3[2:5]) |
Fred Drake | 5935ff0 | 2001-12-19 16:54:23 +0000 | [diff] [blame] | 212 | |
Benjamin Peterson | dc3c239 | 2009-11-19 03:00:02 +0000 | [diff] [blame] | 213 | def test_proxy_unicode(self): |
| 214 | # See bug 5037 |
| 215 | class C(object): |
| 216 | def __str__(self): |
| 217 | return "string" |
| 218 | def __unicode__(self): |
| 219 | return u"unicode" |
| 220 | instance = C() |
Ezio Melotti | aa98058 | 2010-01-23 23:04:36 +0000 | [diff] [blame] | 221 | self.assertIn("__unicode__", dir(weakref.proxy(instance))) |
Benjamin Peterson | dc3c239 | 2009-11-19 03:00:02 +0000 | [diff] [blame] | 222 | self.assertEqual(unicode(weakref.proxy(instance)), u"unicode") |
| 223 | |
Georg Brandl | 88659b0 | 2008-05-20 08:40:43 +0000 | [diff] [blame] | 224 | def test_proxy_index(self): |
| 225 | class C: |
| 226 | def __index__(self): |
| 227 | return 10 |
| 228 | o = C() |
| 229 | p = weakref.proxy(o) |
| 230 | self.assertEqual(operator.index(p), 10) |
| 231 | |
| 232 | def test_proxy_div(self): |
| 233 | class C: |
| 234 | def __floordiv__(self, other): |
| 235 | return 42 |
| 236 | def __ifloordiv__(self, other): |
| 237 | return 21 |
| 238 | o = C() |
| 239 | p = weakref.proxy(o) |
| 240 | self.assertEqual(p // 5, 42) |
| 241 | p //= 5 |
| 242 | self.assertEqual(p, 21) |
| 243 | |
Fred Drake | ea2adc9 | 2004-02-03 19:56:46 +0000 | [diff] [blame] | 244 | # The PyWeakref_* C API is documented as allowing either NULL or |
| 245 | # None as the value for the callback, where either means "no |
| 246 | # callback". The "no callback" ref and proxy objects are supposed |
| 247 | # to be shared so long as they exist by all callers so long as |
Walter Dörwald | da1ad32 | 2006-12-12 21:55:31 +0000 | [diff] [blame] | 248 | # they are active. In Python 2.3.3 and earlier, this guarantee |
Fred Drake | ea2adc9 | 2004-02-03 19:56:46 +0000 | [diff] [blame] | 249 | # was not honored, and was broken in different ways for |
| 250 | # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.) |
| 251 | |
| 252 | def test_shared_ref_without_callback(self): |
| 253 | self.check_shared_without_callback(weakref.ref) |
| 254 | |
| 255 | def test_shared_proxy_without_callback(self): |
| 256 | self.check_shared_without_callback(weakref.proxy) |
| 257 | |
| 258 | def check_shared_without_callback(self, makeref): |
| 259 | o = Object(1) |
| 260 | p1 = makeref(o, None) |
| 261 | p2 = makeref(o, None) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 262 | self.assertIs(p1, p2, "both callbacks were None in the C API") |
Fred Drake | ea2adc9 | 2004-02-03 19:56:46 +0000 | [diff] [blame] | 263 | del p1, p2 |
| 264 | p1 = makeref(o) |
| 265 | p2 = makeref(o, None) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 266 | self.assertIs(p1, p2, "callbacks were NULL, None in the C API") |
Fred Drake | ea2adc9 | 2004-02-03 19:56:46 +0000 | [diff] [blame] | 267 | del p1, p2 |
| 268 | p1 = makeref(o) |
| 269 | p2 = makeref(o) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 270 | self.assertIs(p1, p2, "both callbacks were NULL in the C API") |
Fred Drake | ea2adc9 | 2004-02-03 19:56:46 +0000 | [diff] [blame] | 271 | del p1, p2 |
| 272 | p1 = makeref(o, None) |
| 273 | p2 = makeref(o) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 274 | self.assertIs(p1, p2, "callbacks were None, NULL in the C API") |
Fred Drake | ea2adc9 | 2004-02-03 19:56:46 +0000 | [diff] [blame] | 275 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 276 | def test_callable_proxy(self): |
| 277 | o = Callable() |
| 278 | ref1 = weakref.proxy(o) |
| 279 | |
| 280 | self.check_proxy(o, ref1) |
| 281 | |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 282 | self.assertIs(type(ref1), weakref.CallableProxyType, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 283 | "proxy is not of callable type") |
| 284 | ref1('twinkies!') |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 285 | self.assertEqual(o.bar, 'twinkies!', |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 286 | "call through proxy not passed through to original") |
Fred Drake | 3bb4d21 | 2001-10-18 19:28:29 +0000 | [diff] [blame] | 287 | ref1(x='Splat.') |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 288 | self.assertEqual(o.bar, 'Splat.', |
Fred Drake | 3bb4d21 | 2001-10-18 19:28:29 +0000 | [diff] [blame] | 289 | "call through proxy not passed through to original") |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 290 | |
| 291 | # expect due to too few args |
| 292 | self.assertRaises(TypeError, ref1) |
| 293 | |
| 294 | # expect due to too many args |
| 295 | self.assertRaises(TypeError, ref1, 1, 2, 3) |
| 296 | |
| 297 | def check_proxy(self, o, proxy): |
| 298 | o.foo = 1 |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 299 | self.assertEqual(proxy.foo, 1, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 300 | "proxy does not reflect attribute addition") |
| 301 | o.foo = 2 |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 302 | self.assertEqual(proxy.foo, 2, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 303 | "proxy does not reflect attribute modification") |
| 304 | del o.foo |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 305 | self.assertFalse(hasattr(proxy, 'foo'), |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 306 | "proxy does not reflect attribute removal") |
| 307 | |
| 308 | proxy.foo = 1 |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 309 | self.assertEqual(o.foo, 1, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 310 | "object does not reflect attribute addition via proxy") |
| 311 | proxy.foo = 2 |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 312 | self.assertEqual(o.foo, 2, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 313 | "object does not reflect attribute modification via proxy") |
| 314 | del proxy.foo |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 315 | self.assertFalse(hasattr(o, 'foo'), |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 316 | "object does not reflect attribute removal via proxy") |
| 317 | |
Raymond Hettinger | d693a81 | 2003-06-30 04:18:48 +0000 | [diff] [blame] | 318 | def test_proxy_deletion(self): |
| 319 | # Test clearing of SF bug #762891 |
| 320 | class Foo: |
| 321 | result = None |
| 322 | def __delitem__(self, accessor): |
| 323 | self.result = accessor |
| 324 | g = Foo() |
| 325 | f = weakref.proxy(g) |
| 326 | del f[0] |
| 327 | self.assertEqual(f.result, 0) |
| 328 | |
Raymond Hettinger | e6c470f | 2005-03-27 03:04:54 +0000 | [diff] [blame] | 329 | def test_proxy_bool(self): |
| 330 | # Test clearing of SF bug #1170766 |
| 331 | class List(list): pass |
| 332 | lyst = List() |
| 333 | self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst)) |
| 334 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 335 | def test_getweakrefcount(self): |
| 336 | o = C() |
| 337 | ref1 = weakref.ref(o) |
| 338 | ref2 = weakref.ref(o, self.callback) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 339 | self.assertEqual(weakref.getweakrefcount(o), 2, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 340 | "got wrong number of weak reference objects") |
| 341 | |
| 342 | proxy1 = weakref.proxy(o) |
| 343 | proxy2 = weakref.proxy(o, self.callback) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 344 | self.assertEqual(weakref.getweakrefcount(o), 4, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 345 | "got wrong number of weak reference objects") |
| 346 | |
Fred Drake | ea2adc9 | 2004-02-03 19:56:46 +0000 | [diff] [blame] | 347 | del ref1, ref2, proxy1, proxy2 |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 348 | self.assertEqual(weakref.getweakrefcount(o), 0, |
Fred Drake | ea2adc9 | 2004-02-03 19:56:46 +0000 | [diff] [blame] | 349 | "weak reference objects not unlinked from" |
| 350 | " referent when discarded.") |
| 351 | |
Walter Dörwald | b167b04 | 2003-12-11 12:34:05 +0000 | [diff] [blame] | 352 | # assumes ints do not support weakrefs |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 353 | self.assertEqual(weakref.getweakrefcount(1), 0, |
Walter Dörwald | b167b04 | 2003-12-11 12:34:05 +0000 | [diff] [blame] | 354 | "got wrong number of weak reference objects for int") |
| 355 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 356 | def test_getweakrefs(self): |
| 357 | o = C() |
| 358 | ref1 = weakref.ref(o, self.callback) |
| 359 | ref2 = weakref.ref(o, self.callback) |
| 360 | del ref1 |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 361 | self.assertEqual(weakref.getweakrefs(o), [ref2], |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 362 | "list of refs does not match") |
| 363 | |
| 364 | o = C() |
| 365 | ref1 = weakref.ref(o, self.callback) |
| 366 | ref2 = weakref.ref(o, self.callback) |
| 367 | del ref2 |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 368 | self.assertEqual(weakref.getweakrefs(o), [ref1], |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 369 | "list of refs does not match") |
| 370 | |
Fred Drake | ea2adc9 | 2004-02-03 19:56:46 +0000 | [diff] [blame] | 371 | del ref1 |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 372 | self.assertEqual(weakref.getweakrefs(o), [], |
Fred Drake | ea2adc9 | 2004-02-03 19:56:46 +0000 | [diff] [blame] | 373 | "list of refs not cleared") |
| 374 | |
Walter Dörwald | b167b04 | 2003-12-11 12:34:05 +0000 | [diff] [blame] | 375 | # assumes ints do not support weakrefs |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 376 | self.assertEqual(weakref.getweakrefs(1), [], |
Walter Dörwald | b167b04 | 2003-12-11 12:34:05 +0000 | [diff] [blame] | 377 | "list of refs does not match for int") |
| 378 | |
Fred Drake | 39c27f1 | 2001-10-18 18:06:05 +0000 | [diff] [blame] | 379 | def test_newstyle_number_ops(self): |
| 380 | class F(float): |
| 381 | pass |
| 382 | f = F(2.0) |
| 383 | p = weakref.proxy(f) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 384 | self.assertEqual(p + 1.0, 3.0) |
| 385 | self.assertEqual(1.0 + p, 3.0) # this used to SEGV |
Fred Drake | 39c27f1 | 2001-10-18 18:06:05 +0000 | [diff] [blame] | 386 | |
Fred Drake | 2a64f46 | 2001-12-10 23:46:02 +0000 | [diff] [blame] | 387 | def test_callbacks_protected(self): |
Guido van Rossum | 9eee554 | 2002-08-22 20:21:30 +0000 | [diff] [blame] | 388 | # Callbacks protected from already-set exceptions? |
Fred Drake | 2a64f46 | 2001-12-10 23:46:02 +0000 | [diff] [blame] | 389 | # Regression test for SF bug #478534. |
| 390 | class BogusError(Exception): |
| 391 | pass |
| 392 | data = {} |
| 393 | def remove(k): |
| 394 | del data[k] |
| 395 | def encapsulate(): |
| 396 | f = lambda : () |
| 397 | data[weakref.ref(f, remove)] = None |
| 398 | raise BogusError |
| 399 | try: |
| 400 | encapsulate() |
| 401 | except BogusError: |
| 402 | pass |
| 403 | else: |
| 404 | self.fail("exception not properly restored") |
| 405 | try: |
| 406 | encapsulate() |
| 407 | except BogusError: |
| 408 | pass |
| 409 | else: |
| 410 | self.fail("exception not properly restored") |
| 411 | |
Tim Peters | add09b4 | 2003-11-12 20:43:28 +0000 | [diff] [blame] | 412 | def test_sf_bug_840829(self): |
| 413 | # "weakref callbacks and gc corrupt memory" |
| 414 | # subtype_dealloc erroneously exposed a new-style instance |
| 415 | # already in the process of getting deallocated to gc, |
| 416 | # causing double-deallocation if the instance had a weakref |
| 417 | # callback that triggered gc. |
| 418 | # If the bug exists, there probably won't be an obvious symptom |
| 419 | # in a release build. In a debug build, a segfault will occur |
| 420 | # when the second attempt to remove the instance from the "list |
| 421 | # of all objects" occurs. |
| 422 | |
| 423 | import gc |
| 424 | |
| 425 | class C(object): |
| 426 | pass |
| 427 | |
| 428 | c = C() |
| 429 | wr = weakref.ref(c, lambda ignore: gc.collect()) |
| 430 | del c |
| 431 | |
Tim Peters | f7f9e99 | 2003-11-13 21:59:32 +0000 | [diff] [blame] | 432 | # There endeth the first part. It gets worse. |
| 433 | del wr |
| 434 | |
| 435 | c1 = C() |
| 436 | c1.i = C() |
| 437 | wr = weakref.ref(c1.i, lambda ignore: gc.collect()) |
| 438 | |
| 439 | c2 = C() |
| 440 | c2.c1 = c1 |
| 441 | del c1 # still alive because c2 points to it |
| 442 | |
| 443 | # Now when subtype_dealloc gets called on c2, it's not enough just |
| 444 | # that c2 is immune from gc while the weakref callbacks associated |
| 445 | # with c2 execute (there are none in this 2nd half of the test, btw). |
| 446 | # subtype_dealloc goes on to call the base classes' deallocs too, |
| 447 | # so any gc triggered by weakref callbacks associated with anything |
| 448 | # torn down by a base class dealloc can also trigger double |
| 449 | # deallocation of c2. |
| 450 | del c2 |
Fred Drake | 41deb1e | 2001-02-01 05:27:45 +0000 | [diff] [blame] | 451 | |
Tim Peters | 403a203 | 2003-11-20 21:21:46 +0000 | [diff] [blame] | 452 | def test_callback_in_cycle_1(self): |
| 453 | import gc |
| 454 | |
| 455 | class J(object): |
| 456 | pass |
| 457 | |
| 458 | class II(object): |
| 459 | def acallback(self, ignore): |
| 460 | self.J |
| 461 | |
| 462 | I = II() |
| 463 | I.J = J |
| 464 | I.wr = weakref.ref(J, I.acallback) |
| 465 | |
| 466 | # Now J and II are each in a self-cycle (as all new-style class |
| 467 | # objects are, since their __mro__ points back to them). I holds |
| 468 | # both a weak reference (I.wr) and a strong reference (I.J) to class |
| 469 | # J. I is also in a cycle (I.wr points to a weakref that references |
| 470 | # I.acallback). When we del these three, they all become trash, but |
| 471 | # the cycles prevent any of them from getting cleaned up immediately. |
| 472 | # Instead they have to wait for cyclic gc to deduce that they're |
| 473 | # trash. |
| 474 | # |
| 475 | # gc used to call tp_clear on all of them, and the order in which |
| 476 | # it does that is pretty accidental. The exact order in which we |
| 477 | # built up these things manages to provoke gc into running tp_clear |
| 478 | # in just the right order (I last). Calling tp_clear on II leaves |
| 479 | # behind an insane class object (its __mro__ becomes NULL). Calling |
| 480 | # tp_clear on J breaks its self-cycle, but J doesn't get deleted |
| 481 | # just then because of the strong reference from I.J. Calling |
| 482 | # tp_clear on I starts to clear I's __dict__, and just happens to |
| 483 | # clear I.J first -- I.wr is still intact. That removes the last |
| 484 | # reference to J, which triggers the weakref callback. The callback |
| 485 | # tries to do "self.J", and instances of new-style classes look up |
| 486 | # attributes ("J") in the class dict first. The class (II) wants to |
| 487 | # search II.__mro__, but that's NULL. The result was a segfault in |
| 488 | # a release build, and an assert failure in a debug build. |
| 489 | del I, J, II |
| 490 | gc.collect() |
| 491 | |
| 492 | def test_callback_in_cycle_2(self): |
| 493 | import gc |
| 494 | |
| 495 | # This is just like test_callback_in_cycle_1, except that II is an |
| 496 | # old-style class. The symptom is different then: an instance of an |
| 497 | # old-style class looks in its own __dict__ first. 'J' happens to |
| 498 | # get cleared from I.__dict__ before 'wr', and 'J' was never in II's |
| 499 | # __dict__, so the attribute isn't found. The difference is that |
| 500 | # the old-style II doesn't have a NULL __mro__ (it doesn't have any |
| 501 | # __mro__), so no segfault occurs. Instead it got: |
| 502 | # test_callback_in_cycle_2 (__main__.ReferencesTestCase) ... |
| 503 | # Exception exceptions.AttributeError: |
| 504 | # "II instance has no attribute 'J'" in <bound method II.acallback |
| 505 | # of <?.II instance at 0x00B9B4B8>> ignored |
| 506 | |
| 507 | class J(object): |
| 508 | pass |
| 509 | |
| 510 | class II: |
| 511 | def acallback(self, ignore): |
| 512 | self.J |
| 513 | |
| 514 | I = II() |
| 515 | I.J = J |
| 516 | I.wr = weakref.ref(J, I.acallback) |
| 517 | |
| 518 | del I, J, II |
| 519 | gc.collect() |
| 520 | |
| 521 | def test_callback_in_cycle_3(self): |
| 522 | import gc |
| 523 | |
| 524 | # This one broke the first patch that fixed the last two. In this |
| 525 | # case, the objects reachable from the callback aren't also reachable |
| 526 | # from the object (c1) *triggering* the callback: you can get to |
| 527 | # c1 from c2, but not vice-versa. The result was that c2's __dict__ |
| 528 | # got tp_clear'ed by the time the c2.cb callback got invoked. |
| 529 | |
| 530 | class C: |
| 531 | def cb(self, ignore): |
| 532 | self.me |
| 533 | self.c1 |
| 534 | self.wr |
| 535 | |
| 536 | c1, c2 = C(), C() |
| 537 | |
| 538 | c2.me = c2 |
| 539 | c2.c1 = c1 |
| 540 | c2.wr = weakref.ref(c1, c2.cb) |
| 541 | |
| 542 | del c1, c2 |
| 543 | gc.collect() |
| 544 | |
| 545 | def test_callback_in_cycle_4(self): |
| 546 | import gc |
| 547 | |
| 548 | # Like test_callback_in_cycle_3, except c2 and c1 have different |
| 549 | # classes. c2's class (C) isn't reachable from c1 then, so protecting |
| 550 | # objects reachable from the dying object (c1) isn't enough to stop |
| 551 | # c2's class (C) from getting tp_clear'ed before c2.cb is invoked. |
| 552 | # The result was a segfault (C.__mro__ was NULL when the callback |
| 553 | # tried to look up self.me). |
| 554 | |
| 555 | class C(object): |
| 556 | def cb(self, ignore): |
| 557 | self.me |
| 558 | self.c1 |
| 559 | self.wr |
| 560 | |
| 561 | class D: |
| 562 | pass |
| 563 | |
| 564 | c1, c2 = D(), C() |
| 565 | |
| 566 | c2.me = c2 |
| 567 | c2.c1 = c1 |
| 568 | c2.wr = weakref.ref(c1, c2.cb) |
| 569 | |
| 570 | del c1, c2, C, D |
| 571 | gc.collect() |
| 572 | |
| 573 | def test_callback_in_cycle_resurrection(self): |
| 574 | import gc |
| 575 | |
| 576 | # Do something nasty in a weakref callback: resurrect objects |
| 577 | # from dead cycles. For this to be attempted, the weakref and |
| 578 | # its callback must also be part of the cyclic trash (else the |
| 579 | # objects reachable via the callback couldn't be in cyclic trash |
| 580 | # to begin with -- the callback would act like an external root). |
| 581 | # But gc clears trash weakrefs with callbacks early now, which |
| 582 | # disables the callbacks, so the callbacks shouldn't get called |
| 583 | # at all (and so nothing actually gets resurrected). |
| 584 | |
| 585 | alist = [] |
| 586 | class C(object): |
| 587 | def __init__(self, value): |
| 588 | self.attribute = value |
| 589 | |
| 590 | def acallback(self, ignore): |
| 591 | alist.append(self.c) |
| 592 | |
| 593 | c1, c2 = C(1), C(2) |
| 594 | c1.c = c2 |
| 595 | c2.c = c1 |
| 596 | c1.wr = weakref.ref(c2, c1.acallback) |
| 597 | c2.wr = weakref.ref(c1, c2.acallback) |
| 598 | |
| 599 | def C_went_away(ignore): |
| 600 | alist.append("C went away") |
| 601 | wr = weakref.ref(C, C_went_away) |
| 602 | |
| 603 | del c1, c2, C # make them all trash |
| 604 | self.assertEqual(alist, []) # del isn't enough to reclaim anything |
| 605 | |
| 606 | gc.collect() |
| 607 | # c1.wr and c2.wr were part of the cyclic trash, so should have |
| 608 | # been cleared without their callbacks executing. OTOH, the weakref |
| 609 | # to C is bound to a function local (wr), and wasn't trash, so that |
| 610 | # callback should have been invoked when C went away. |
| 611 | self.assertEqual(alist, ["C went away"]) |
| 612 | # The remaining weakref should be dead now (its callback ran). |
| 613 | self.assertEqual(wr(), None) |
| 614 | |
| 615 | del alist[:] |
| 616 | gc.collect() |
| 617 | self.assertEqual(alist, []) |
| 618 | |
| 619 | def test_callbacks_on_callback(self): |
| 620 | import gc |
| 621 | |
| 622 | # Set up weakref callbacks *on* weakref callbacks. |
| 623 | alist = [] |
| 624 | def safe_callback(ignore): |
| 625 | alist.append("safe_callback called") |
| 626 | |
| 627 | class C(object): |
| 628 | def cb(self, ignore): |
| 629 | alist.append("cb called") |
| 630 | |
| 631 | c, d = C(), C() |
| 632 | c.other = d |
| 633 | d.other = c |
| 634 | callback = c.cb |
| 635 | c.wr = weakref.ref(d, callback) # this won't trigger |
| 636 | d.wr = weakref.ref(callback, d.cb) # ditto |
| 637 | external_wr = weakref.ref(callback, safe_callback) # but this will |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 638 | self.assertIs(external_wr(), callback) |
Tim Peters | 403a203 | 2003-11-20 21:21:46 +0000 | [diff] [blame] | 639 | |
| 640 | # The weakrefs attached to c and d should get cleared, so that |
| 641 | # C.cb is never called. But external_wr isn't part of the cyclic |
| 642 | # trash, and no cyclic trash is reachable from it, so safe_callback |
| 643 | # should get invoked when the bound method object callback (c.cb) |
| 644 | # -- which is itself a callback, and also part of the cyclic trash -- |
| 645 | # gets reclaimed at the end of gc. |
| 646 | |
| 647 | del callback, c, d, C |
| 648 | self.assertEqual(alist, []) # del isn't enough to clean up cycles |
| 649 | gc.collect() |
| 650 | self.assertEqual(alist, ["safe_callback called"]) |
| 651 | self.assertEqual(external_wr(), None) |
| 652 | |
| 653 | del alist[:] |
| 654 | gc.collect() |
| 655 | self.assertEqual(alist, []) |
| 656 | |
Fred Drake | bc875f5 | 2004-02-04 23:14:14 +0000 | [diff] [blame] | 657 | def test_gc_during_ref_creation(self): |
| 658 | self.check_gc_during_creation(weakref.ref) |
| 659 | |
| 660 | def test_gc_during_proxy_creation(self): |
| 661 | self.check_gc_during_creation(weakref.proxy) |
| 662 | |
| 663 | def check_gc_during_creation(self, makeref): |
| 664 | thresholds = gc.get_threshold() |
| 665 | gc.set_threshold(1, 1, 1) |
| 666 | gc.collect() |
Fred Drake | 55cf434 | 2004-02-13 19:21:57 +0000 | [diff] [blame] | 667 | class A: |
| 668 | pass |
Fred Drake | bc875f5 | 2004-02-04 23:14:14 +0000 | [diff] [blame] | 669 | |
| 670 | def callback(*args): |
| 671 | pass |
| 672 | |
Fred Drake | 55cf434 | 2004-02-13 19:21:57 +0000 | [diff] [blame] | 673 | referenced = A() |
Fred Drake | bc875f5 | 2004-02-04 23:14:14 +0000 | [diff] [blame] | 674 | |
Fred Drake | 55cf434 | 2004-02-13 19:21:57 +0000 | [diff] [blame] | 675 | a = A() |
Fred Drake | bc875f5 | 2004-02-04 23:14:14 +0000 | [diff] [blame] | 676 | a.a = a |
| 677 | a.wr = makeref(referenced) |
| 678 | |
| 679 | try: |
| 680 | # now make sure the object and the ref get labeled as |
| 681 | # cyclic trash: |
Fred Drake | 55cf434 | 2004-02-13 19:21:57 +0000 | [diff] [blame] | 682 | a = A() |
| 683 | weakref.ref(referenced, callback) |
Fred Drake | bc875f5 | 2004-02-04 23:14:14 +0000 | [diff] [blame] | 684 | |
| 685 | finally: |
| 686 | gc.set_threshold(*thresholds) |
| 687 | |
Brett Cannon | f5bee30 | 2007-01-23 23:21:22 +0000 | [diff] [blame] | 688 | def test_ref_created_during_del(self): |
| 689 | # Bug #1377858 |
| 690 | # A weakref created in an object's __del__() would crash the |
| 691 | # interpreter when the weakref was cleaned up since it would refer to |
| 692 | # non-existent memory. This test should not segfault the interpreter. |
| 693 | class Target(object): |
| 694 | def __del__(self): |
| 695 | global ref_from_del |
| 696 | ref_from_del = weakref.ref(self) |
| 697 | |
| 698 | w = Target() |
| 699 | |
Benjamin Peterson | 97179b0 | 2008-09-09 20:55:01 +0000 | [diff] [blame] | 700 | def test_init(self): |
| 701 | # Issue 3634 |
| 702 | # <weakref to class>.__init__() doesn't check errors correctly |
| 703 | r = weakref.ref(Exception) |
| 704 | self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0) |
| 705 | # No exception should be raised here |
| 706 | gc.collect() |
| 707 | |
Antoine Pitrou | a57df2c | 2010-03-31 21:32:15 +0000 | [diff] [blame] | 708 | def test_classes(self): |
| 709 | # Check that both old-style classes and new-style classes |
| 710 | # are weakrefable. |
| 711 | class A(object): |
| 712 | pass |
| 713 | class B: |
| 714 | pass |
| 715 | l = [] |
| 716 | weakref.ref(int) |
| 717 | a = weakref.ref(A, l.append) |
| 718 | A = None |
| 719 | gc.collect() |
| 720 | self.assertEqual(a(), None) |
| 721 | self.assertEqual(l, [a]) |
| 722 | b = weakref.ref(B, l.append) |
| 723 | B = None |
| 724 | gc.collect() |
| 725 | self.assertEqual(b(), None) |
| 726 | self.assertEqual(l, [a, b]) |
| 727 | |
Antoine Pitrou | b704eab | 2012-11-11 19:36:51 +0100 | [diff] [blame] | 728 | def test_equality(self): |
| 729 | # Alive weakrefs defer equality testing to their underlying object. |
| 730 | x = Object(1) |
| 731 | y = Object(1) |
| 732 | z = Object(2) |
| 733 | a = weakref.ref(x) |
| 734 | b = weakref.ref(y) |
| 735 | c = weakref.ref(z) |
| 736 | d = weakref.ref(x) |
| 737 | # Note how we directly test the operators here, to stress both |
| 738 | # __eq__ and __ne__. |
| 739 | self.assertTrue(a == b) |
| 740 | self.assertFalse(a != b) |
| 741 | self.assertFalse(a == c) |
| 742 | self.assertTrue(a != c) |
| 743 | self.assertTrue(a == d) |
| 744 | self.assertFalse(a != d) |
| 745 | del x, y, z |
| 746 | gc.collect() |
| 747 | for r in a, b, c: |
| 748 | # Sanity check |
| 749 | self.assertIs(r(), None) |
| 750 | # Dead weakrefs compare by identity: whether `a` and `d` are the |
| 751 | # same weakref object is an implementation detail, since they pointed |
| 752 | # to the same original object and didn't have a callback. |
| 753 | # (see issue #16453). |
| 754 | self.assertFalse(a == b) |
| 755 | self.assertTrue(a != b) |
| 756 | self.assertFalse(a == c) |
| 757 | self.assertTrue(a != c) |
| 758 | self.assertEqual(a == d, a is d) |
| 759 | self.assertEqual(a != d, a is not d) |
| 760 | |
| 761 | def test_hashing(self): |
| 762 | # Alive weakrefs hash the same as the underlying object |
| 763 | x = Object(42) |
| 764 | y = Object(42) |
| 765 | a = weakref.ref(x) |
| 766 | b = weakref.ref(y) |
| 767 | self.assertEqual(hash(a), hash(42)) |
| 768 | del x, y |
| 769 | gc.collect() |
| 770 | # Dead weakrefs: |
| 771 | # - retain their hash is they were hashed when alive; |
| 772 | # - otherwise, cannot be hashed. |
| 773 | self.assertEqual(hash(a), hash(42)) |
| 774 | self.assertRaises(TypeError, hash, b) |
| 775 | |
Antoine Pitrou | d38c990 | 2012-12-08 21:15:26 +0100 | [diff] [blame] | 776 | def test_trashcan_16602(self): |
| 777 | # Issue #16602: when a weakref's target was part of a long |
| 778 | # deallocation chain, the trashcan mechanism could delay clearing |
| 779 | # of the weakref and make the target object visible from outside |
| 780 | # code even though its refcount had dropped to 0. A crash ensued. |
| 781 | class C(object): |
| 782 | def __init__(self, parent): |
| 783 | if not parent: |
| 784 | return |
| 785 | wself = weakref.ref(self) |
| 786 | def cb(wparent): |
| 787 | o = wself() |
| 788 | self.wparent = weakref.ref(parent, cb) |
| 789 | |
| 790 | d = weakref.WeakKeyDictionary() |
| 791 | root = c = C(None) |
| 792 | for n in range(100): |
| 793 | d[c] = c = C(c) |
| 794 | del root |
| 795 | gc.collect() |
| 796 | |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 797 | |
Amaury Forgeot d'Arc | a8919fe | 2008-06-16 19:12:42 +0000 | [diff] [blame] | 798 | class SubclassableWeakrefTestCase(TestBase): |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 799 | |
| 800 | def test_subclass_refs(self): |
| 801 | class MyRef(weakref.ref): |
| 802 | def __init__(self, ob, callback=None, value=42): |
| 803 | self.value = value |
| 804 | super(MyRef, self).__init__(ob, callback) |
| 805 | def __call__(self): |
| 806 | self.called = True |
| 807 | return super(MyRef, self).__call__() |
| 808 | o = Object("foo") |
| 809 | mr = MyRef(o, value=24) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 810 | self.assertIs(mr(), o) |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 811 | self.assertTrue(mr.called) |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 812 | self.assertEqual(mr.value, 24) |
| 813 | del o |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 814 | self.assertIsNone(mr()) |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 815 | self.assertTrue(mr.called) |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 816 | |
| 817 | def test_subclass_refs_dont_replace_standard_refs(self): |
| 818 | class MyRef(weakref.ref): |
| 819 | pass |
| 820 | o = Object(42) |
| 821 | r1 = MyRef(o) |
| 822 | r2 = weakref.ref(o) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 823 | self.assertIsNot(r1, r2) |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 824 | self.assertEqual(weakref.getweakrefs(o), [r2, r1]) |
| 825 | self.assertEqual(weakref.getweakrefcount(o), 2) |
| 826 | r3 = MyRef(o) |
| 827 | self.assertEqual(weakref.getweakrefcount(o), 3) |
| 828 | refs = weakref.getweakrefs(o) |
| 829 | self.assertEqual(len(refs), 3) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 830 | self.assertIs(r2, refs[0]) |
Ezio Melotti | aa98058 | 2010-01-23 23:04:36 +0000 | [diff] [blame] | 831 | self.assertIn(r1, refs[1:]) |
| 832 | self.assertIn(r3, refs[1:]) |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 833 | |
| 834 | def test_subclass_refs_dont_conflate_callbacks(self): |
| 835 | class MyRef(weakref.ref): |
| 836 | pass |
| 837 | o = Object(42) |
| 838 | r1 = MyRef(o, id) |
| 839 | r2 = MyRef(o, str) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 840 | self.assertIsNot(r1, r2) |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 841 | refs = weakref.getweakrefs(o) |
Ezio Melotti | aa98058 | 2010-01-23 23:04:36 +0000 | [diff] [blame] | 842 | self.assertIn(r1, refs) |
| 843 | self.assertIn(r2, refs) |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 844 | |
| 845 | def test_subclass_refs_with_slots(self): |
| 846 | class MyRef(weakref.ref): |
| 847 | __slots__ = "slot1", "slot2" |
| 848 | def __new__(type, ob, callback, slot1, slot2): |
| 849 | return weakref.ref.__new__(type, ob, callback) |
| 850 | def __init__(self, ob, callback, slot1, slot2): |
| 851 | self.slot1 = slot1 |
| 852 | self.slot2 = slot2 |
| 853 | def meth(self): |
| 854 | return self.slot1 + self.slot2 |
| 855 | o = Object(42) |
| 856 | r = MyRef(o, None, "abc", "def") |
| 857 | self.assertEqual(r.slot1, "abc") |
| 858 | self.assertEqual(r.slot2, "def") |
| 859 | self.assertEqual(r.meth(), "abcdef") |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 860 | self.assertFalse(hasattr(r, "__dict__")) |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 861 | |
Amaury Forgeot d'Arc | a8919fe | 2008-06-16 19:12:42 +0000 | [diff] [blame] | 862 | def test_subclass_refs_with_cycle(self): |
| 863 | # Bug #3110 |
| 864 | # An instance of a weakref subclass can have attributes. |
| 865 | # If such a weakref holds the only strong reference to the object, |
| 866 | # deleting the weakref will delete the object. In this case, |
| 867 | # the callback must not be called, because the ref object is |
| 868 | # being deleted. |
| 869 | class MyRef(weakref.ref): |
| 870 | pass |
| 871 | |
| 872 | # Use a local callback, for "regrtest -R::" |
| 873 | # to detect refcounting problems |
| 874 | def callback(w): |
| 875 | self.cbcalled += 1 |
| 876 | |
| 877 | o = C() |
| 878 | r1 = MyRef(o, callback) |
| 879 | r1.o = o |
| 880 | del o |
| 881 | |
| 882 | del r1 # Used to crash here |
| 883 | |
| 884 | self.assertEqual(self.cbcalled, 0) |
| 885 | |
| 886 | # Same test, with two weakrefs to the same object |
| 887 | # (since code paths are different) |
| 888 | o = C() |
| 889 | r1 = MyRef(o, callback) |
| 890 | r2 = MyRef(o, callback) |
| 891 | r1.r = r2 |
| 892 | r2.o = o |
| 893 | del o |
| 894 | del r2 |
| 895 | |
| 896 | del r1 # Used to crash here |
| 897 | |
| 898 | self.assertEqual(self.cbcalled, 0) |
| 899 | |
Fred Drake | 0a4dd39 | 2004-07-02 18:57:45 +0000 | [diff] [blame] | 900 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 901 | class MappingTestCase(TestBase): |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 902 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 903 | COUNT = 10 |
| 904 | |
Antoine Pitrou | c56bca3 | 2012-03-01 16:26:35 +0100 | [diff] [blame] | 905 | def check_len_cycles(self, dict_type, cons): |
| 906 | N = 20 |
| 907 | items = [RefCycle() for i in range(N)] |
Kristján Valur Jónsson | 222b284 | 2013-12-05 10:03:45 +0000 | [diff] [blame] | 908 | dct = dict_type(cons(i, o) for i, o in enumerate(items)) |
Antoine Pitrou | c56bca3 | 2012-03-01 16:26:35 +0100 | [diff] [blame] | 909 | # Keep an iterator alive |
| 910 | it = dct.iteritems() |
| 911 | try: |
| 912 | next(it) |
| 913 | except StopIteration: |
| 914 | pass |
| 915 | del items |
| 916 | gc.collect() |
| 917 | n1 = len(dct) |
Kristján Valur Jónsson | 222b284 | 2013-12-05 10:03:45 +0000 | [diff] [blame] | 918 | list(it) |
Antoine Pitrou | c56bca3 | 2012-03-01 16:26:35 +0100 | [diff] [blame] | 919 | del it |
| 920 | gc.collect() |
| 921 | n2 = len(dct) |
Kristján Valur Jónsson | 222b284 | 2013-12-05 10:03:45 +0000 | [diff] [blame] | 922 | # iteration should prevent garbage collection here |
| 923 | # Note that this is a test on an implementation detail. The requirement |
| 924 | # is only to provide stable iteration, not that the size of the container |
| 925 | # stay fixed. |
| 926 | self.assertEqual(n1, 20) |
| 927 | #self.assertIn(n1, (0, 1)) |
Antoine Pitrou | c56bca3 | 2012-03-01 16:26:35 +0100 | [diff] [blame] | 928 | self.assertEqual(n2, 0) |
| 929 | |
| 930 | def test_weak_keyed_len_cycles(self): |
Kristján Valur Jónsson | 222b284 | 2013-12-05 10:03:45 +0000 | [diff] [blame] | 931 | self.check_len_cycles(weakref.WeakKeyDictionary, lambda n, k: (k, n)) |
Antoine Pitrou | c56bca3 | 2012-03-01 16:26:35 +0100 | [diff] [blame] | 932 | |
| 933 | def test_weak_valued_len_cycles(self): |
Kristján Valur Jónsson | 222b284 | 2013-12-05 10:03:45 +0000 | [diff] [blame] | 934 | self.check_len_cycles(weakref.WeakValueDictionary, lambda n, k: (n, k)) |
Antoine Pitrou | c56bca3 | 2012-03-01 16:26:35 +0100 | [diff] [blame] | 935 | |
| 936 | def check_len_race(self, dict_type, cons): |
| 937 | # Extended sanity checks for len() in the face of cyclic collection |
| 938 | self.addCleanup(gc.set_threshold, *gc.get_threshold()) |
| 939 | for th in range(1, 100): |
| 940 | N = 20 |
| 941 | gc.collect(0) |
| 942 | gc.set_threshold(th, th, th) |
| 943 | items = [RefCycle() for i in range(N)] |
| 944 | dct = dict_type(cons(o) for o in items) |
| 945 | del items |
| 946 | # All items will be collected at next garbage collection pass |
| 947 | it = dct.iteritems() |
| 948 | try: |
| 949 | next(it) |
| 950 | except StopIteration: |
| 951 | pass |
| 952 | n1 = len(dct) |
| 953 | del it |
| 954 | n2 = len(dct) |
| 955 | self.assertGreaterEqual(n1, 0) |
| 956 | self.assertLessEqual(n1, N) |
| 957 | self.assertGreaterEqual(n2, 0) |
| 958 | self.assertLessEqual(n2, n1) |
| 959 | |
| 960 | def test_weak_keyed_len_race(self): |
| 961 | self.check_len_race(weakref.WeakKeyDictionary, lambda k: (k, 1)) |
| 962 | |
| 963 | def test_weak_valued_len_race(self): |
| 964 | self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k)) |
| 965 | |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 966 | def test_weak_values(self): |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 967 | # |
| 968 | # This exercises d.copy(), d.items(), d[], del d[], len(d). |
| 969 | # |
| 970 | dict, objects = self.make_weak_valued_dict() |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 971 | for o in objects: |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 972 | self.assertEqual(weakref.getweakrefcount(o), 1, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 973 | "wrong number of weak references to %r!" % o) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 974 | self.assertIs(o, dict[o.arg], |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 975 | "wrong object returned by weak dict!") |
| 976 | items1 = dict.items() |
| 977 | items2 = dict.copy().items() |
| 978 | items1.sort() |
| 979 | items2.sort() |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 980 | self.assertEqual(items1, items2, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 981 | "cloning of weak-valued dictionary did not work!") |
| 982 | del items1, items2 |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 983 | self.assertEqual(len(dict), self.COUNT) |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 984 | del objects[0] |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 985 | self.assertEqual(len(dict), (self.COUNT - 1), |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 986 | "deleting object did not cause dictionary update") |
| 987 | del objects, o |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 988 | self.assertEqual(len(dict), 0, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 989 | "deleting the values did not clear the dictionary") |
Fred Drake | 4fd06e0 | 2001-08-03 04:11:27 +0000 | [diff] [blame] | 990 | # regression on SF bug #447152: |
| 991 | dict = weakref.WeakValueDictionary() |
| 992 | self.assertRaises(KeyError, dict.__getitem__, 1) |
| 993 | dict[2] = C() |
| 994 | self.assertRaises(KeyError, dict.__getitem__, 2) |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 995 | |
| 996 | def test_weak_keys(self): |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 997 | # |
| 998 | # This exercises d.copy(), d.items(), d[] = v, d[], del d[], |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 999 | # len(d), in d. |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 1000 | # |
| 1001 | dict, objects = self.make_weak_keyed_dict() |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 1002 | for o in objects: |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1003 | self.assertEqual(weakref.getweakrefcount(o), 1, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 1004 | "wrong number of weak references to %r!" % o) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1005 | self.assertIs(o.arg, dict[o], |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 1006 | "wrong object returned by weak dict!") |
| 1007 | items1 = dict.items() |
| 1008 | items2 = dict.copy().items() |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1009 | self.assertEqual(set(items1), set(items2), |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 1010 | "cloning of weak-keyed dictionary did not work!") |
| 1011 | del items1, items2 |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1012 | self.assertEqual(len(dict), self.COUNT) |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 1013 | del objects[0] |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1014 | self.assertEqual(len(dict), (self.COUNT - 1), |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 1015 | "deleting object did not cause dictionary update") |
| 1016 | del objects, o |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1017 | self.assertEqual(len(dict), 0, |
Fred Drake | b0fefc5 | 2001-03-23 04:22:45 +0000 | [diff] [blame] | 1018 | "deleting the keys did not clear the dictionary") |
Fred Drake | 752eda4 | 2001-11-06 16:38:34 +0000 | [diff] [blame] | 1019 | o = Object(42) |
| 1020 | dict[o] = "What is the meaning of the universe?" |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 1021 | self.assertIn(o, dict) |
| 1022 | self.assertNotIn(34, dict) |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 1023 | |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 1024 | def test_weak_keyed_iters(self): |
| 1025 | dict, objects = self.make_weak_keyed_dict() |
| 1026 | self.check_iters(dict) |
| 1027 | |
Fred Drake | 017e68c | 2006-05-02 06:53:59 +0000 | [diff] [blame] | 1028 | # Test keyrefs() |
| 1029 | refs = dict.keyrefs() |
| 1030 | self.assertEqual(len(refs), len(objects)) |
| 1031 | objects2 = list(objects) |
| 1032 | for wr in refs: |
| 1033 | ob = wr() |
Ezio Melotti | aa98058 | 2010-01-23 23:04:36 +0000 | [diff] [blame] | 1034 | self.assertIn(ob, dict) |
Fred Drake | 017e68c | 2006-05-02 06:53:59 +0000 | [diff] [blame] | 1035 | self.assertEqual(ob.arg, dict[ob]) |
| 1036 | objects2.remove(ob) |
| 1037 | self.assertEqual(len(objects2), 0) |
| 1038 | |
| 1039 | # Test iterkeyrefs() |
| 1040 | objects2 = list(objects) |
| 1041 | self.assertEqual(len(list(dict.iterkeyrefs())), len(objects)) |
| 1042 | for wr in dict.iterkeyrefs(): |
| 1043 | ob = wr() |
Ezio Melotti | aa98058 | 2010-01-23 23:04:36 +0000 | [diff] [blame] | 1044 | self.assertIn(ob, dict) |
Fred Drake | 017e68c | 2006-05-02 06:53:59 +0000 | [diff] [blame] | 1045 | self.assertEqual(ob.arg, dict[ob]) |
| 1046 | objects2.remove(ob) |
| 1047 | self.assertEqual(len(objects2), 0) |
| 1048 | |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 1049 | def test_weak_valued_iters(self): |
| 1050 | dict, objects = self.make_weak_valued_dict() |
| 1051 | self.check_iters(dict) |
| 1052 | |
Fred Drake | 017e68c | 2006-05-02 06:53:59 +0000 | [diff] [blame] | 1053 | # Test valuerefs() |
| 1054 | refs = dict.valuerefs() |
| 1055 | self.assertEqual(len(refs), len(objects)) |
| 1056 | objects2 = list(objects) |
| 1057 | for wr in refs: |
| 1058 | ob = wr() |
| 1059 | self.assertEqual(ob, dict[ob.arg]) |
| 1060 | self.assertEqual(ob.arg, dict[ob.arg].arg) |
| 1061 | objects2.remove(ob) |
| 1062 | self.assertEqual(len(objects2), 0) |
| 1063 | |
| 1064 | # Test itervaluerefs() |
| 1065 | objects2 = list(objects) |
| 1066 | self.assertEqual(len(list(dict.itervaluerefs())), len(objects)) |
| 1067 | for wr in dict.itervaluerefs(): |
| 1068 | ob = wr() |
| 1069 | self.assertEqual(ob, dict[ob.arg]) |
| 1070 | self.assertEqual(ob.arg, dict[ob.arg].arg) |
| 1071 | objects2.remove(ob) |
| 1072 | self.assertEqual(len(objects2), 0) |
| 1073 | |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 1074 | def check_iters(self, dict): |
| 1075 | # item iterator: |
| 1076 | items = dict.items() |
| 1077 | for item in dict.iteritems(): |
| 1078 | items.remove(item) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1079 | self.assertEqual(len(items), 0, "iteritems() did not touch all items") |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 1080 | |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 1081 | # key iterator, via __iter__(): |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 1082 | keys = dict.keys() |
| 1083 | for k in dict: |
| 1084 | keys.remove(k) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1085 | self.assertEqual(len(keys), 0, "__iter__() did not touch all keys") |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 1086 | |
| 1087 | # key iterator, via iterkeys(): |
| 1088 | keys = dict.keys() |
| 1089 | for k in dict.iterkeys(): |
| 1090 | keys.remove(k) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1091 | self.assertEqual(len(keys), 0, "iterkeys() did not touch all keys") |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 1092 | |
| 1093 | # value iterator: |
| 1094 | values = dict.values() |
| 1095 | for v in dict.itervalues(): |
| 1096 | values.remove(v) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1097 | self.assertEqual(len(values), 0, |
Fred Drake | f425b1e | 2003-07-14 21:37:17 +0000 | [diff] [blame] | 1098 | "itervalues() did not touch all values") |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 1099 | |
Kristján Valur Jónsson | 222b284 | 2013-12-05 10:03:45 +0000 | [diff] [blame] | 1100 | def check_weak_destroy_while_iterating(self, dict, objects, iter_name): |
| 1101 | n = len(dict) |
| 1102 | it = iter(getattr(dict, iter_name)()) |
| 1103 | next(it) # Trigger internal iteration |
| 1104 | # Destroy an object |
| 1105 | del objects[-1] |
| 1106 | gc.collect() # just in case |
| 1107 | # We have removed either the first consumed object, or another one |
| 1108 | self.assertIn(len(list(it)), [len(objects), len(objects) - 1]) |
| 1109 | del it |
| 1110 | # The removal has been committed |
| 1111 | self.assertEqual(len(dict), n - 1) |
| 1112 | |
| 1113 | def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext): |
| 1114 | # Check that we can explicitly mutate the weak dict without |
| 1115 | # interfering with delayed removal. |
| 1116 | # `testcontext` should create an iterator, destroy one of the |
| 1117 | # weakref'ed objects and then return a new key/value pair corresponding |
| 1118 | # to the destroyed object. |
| 1119 | with testcontext() as (k, v): |
| 1120 | self.assertFalse(k in dict) |
| 1121 | with testcontext() as (k, v): |
| 1122 | self.assertRaises(KeyError, dict.__delitem__, k) |
| 1123 | self.assertFalse(k in dict) |
| 1124 | with testcontext() as (k, v): |
| 1125 | self.assertRaises(KeyError, dict.pop, k) |
| 1126 | self.assertFalse(k in dict) |
| 1127 | with testcontext() as (k, v): |
| 1128 | dict[k] = v |
| 1129 | self.assertEqual(dict[k], v) |
| 1130 | ddict = copy.copy(dict) |
| 1131 | with testcontext() as (k, v): |
| 1132 | dict.update(ddict) |
| 1133 | self.assertEqual(dict, ddict) |
| 1134 | with testcontext() as (k, v): |
| 1135 | dict.clear() |
| 1136 | self.assertEqual(len(dict), 0) |
| 1137 | |
| 1138 | def test_weak_keys_destroy_while_iterating(self): |
| 1139 | # Issue #7105: iterators shouldn't crash when a key is implicitly removed |
| 1140 | dict, objects = self.make_weak_keyed_dict() |
| 1141 | self.check_weak_destroy_while_iterating(dict, objects, 'iterkeys') |
| 1142 | self.check_weak_destroy_while_iterating(dict, objects, 'iteritems') |
| 1143 | self.check_weak_destroy_while_iterating(dict, objects, 'itervalues') |
| 1144 | self.check_weak_destroy_while_iterating(dict, objects, 'iterkeyrefs') |
| 1145 | dict, objects = self.make_weak_keyed_dict() |
| 1146 | @contextlib.contextmanager |
| 1147 | def testcontext(): |
| 1148 | try: |
| 1149 | it = iter(dict.iteritems()) |
| 1150 | next(it) |
| 1151 | # Schedule a key/value for removal and recreate it |
| 1152 | v = objects.pop().arg |
| 1153 | gc.collect() # just in case |
| 1154 | yield Object(v), v |
| 1155 | finally: |
| 1156 | it = None # should commit all removals |
Benjamin Peterson | 8a4448c | 2014-08-24 18:02:15 -0500 | [diff] [blame] | 1157 | gc.collect() |
Kristján Valur Jónsson | 222b284 | 2013-12-05 10:03:45 +0000 | [diff] [blame] | 1158 | self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext) |
| 1159 | |
| 1160 | def test_weak_values_destroy_while_iterating(self): |
| 1161 | # Issue #7105: iterators shouldn't crash when a key is implicitly removed |
| 1162 | dict, objects = self.make_weak_valued_dict() |
| 1163 | self.check_weak_destroy_while_iterating(dict, objects, 'iterkeys') |
| 1164 | self.check_weak_destroy_while_iterating(dict, objects, 'iteritems') |
| 1165 | self.check_weak_destroy_while_iterating(dict, objects, 'itervalues') |
| 1166 | self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs') |
| 1167 | dict, objects = self.make_weak_valued_dict() |
| 1168 | @contextlib.contextmanager |
| 1169 | def testcontext(): |
| 1170 | try: |
| 1171 | it = iter(dict.iteritems()) |
| 1172 | next(it) |
| 1173 | # Schedule a key/value for removal and recreate it |
| 1174 | k = objects.pop().arg |
| 1175 | gc.collect() # just in case |
| 1176 | yield k, Object(k) |
| 1177 | finally: |
| 1178 | it = None # should commit all removals |
Benjamin Peterson | 8a4448c | 2014-08-24 18:02:15 -0500 | [diff] [blame] | 1179 | gc.collect() |
Kristján Valur Jónsson | 222b284 | 2013-12-05 10:03:45 +0000 | [diff] [blame] | 1180 | self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext) |
| 1181 | |
Guido van Rossum | 009afb7 | 2002-06-10 20:00:52 +0000 | [diff] [blame] | 1182 | def test_make_weak_keyed_dict_from_dict(self): |
| 1183 | o = Object(3) |
| 1184 | dict = weakref.WeakKeyDictionary({o:364}) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1185 | self.assertEqual(dict[o], 364) |
Guido van Rossum | 009afb7 | 2002-06-10 20:00:52 +0000 | [diff] [blame] | 1186 | |
| 1187 | def test_make_weak_keyed_dict_from_weak_keyed_dict(self): |
| 1188 | o = Object(3) |
| 1189 | dict = weakref.WeakKeyDictionary({o:364}) |
| 1190 | dict2 = weakref.WeakKeyDictionary(dict) |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1191 | self.assertEqual(dict[o], 364) |
Guido van Rossum | 009afb7 | 2002-06-10 20:00:52 +0000 | [diff] [blame] | 1192 | |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 1193 | def make_weak_keyed_dict(self): |
| 1194 | dict = weakref.WeakKeyDictionary() |
| 1195 | objects = map(Object, range(self.COUNT)) |
| 1196 | for o in objects: |
| 1197 | dict[o] = o.arg |
| 1198 | return dict, objects |
| 1199 | |
| 1200 | def make_weak_valued_dict(self): |
| 1201 | dict = weakref.WeakValueDictionary() |
| 1202 | objects = map(Object, range(self.COUNT)) |
| 1203 | for o in objects: |
| 1204 | dict[o.arg] = o |
| 1205 | return dict, objects |
| 1206 | |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 1207 | def check_popitem(self, klass, key1, value1, key2, value2): |
| 1208 | weakdict = klass() |
| 1209 | weakdict[key1] = value1 |
| 1210 | weakdict[key2] = value2 |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1211 | self.assertEqual(len(weakdict), 2) |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 1212 | k, v = weakdict.popitem() |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1213 | self.assertEqual(len(weakdict), 1) |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 1214 | if k is key1: |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1215 | self.assertIs(v, value1) |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 1216 | else: |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1217 | self.assertIs(v, value2) |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 1218 | k, v = weakdict.popitem() |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1219 | self.assertEqual(len(weakdict), 0) |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 1220 | if k is key1: |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1221 | self.assertIs(v, value1) |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 1222 | else: |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1223 | self.assertIs(v, value2) |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 1224 | |
| 1225 | def test_weak_valued_dict_popitem(self): |
| 1226 | self.check_popitem(weakref.WeakValueDictionary, |
| 1227 | "key1", C(), "key2", C()) |
| 1228 | |
| 1229 | def test_weak_keyed_dict_popitem(self): |
| 1230 | self.check_popitem(weakref.WeakKeyDictionary, |
| 1231 | C(), "value 1", C(), "value 2") |
| 1232 | |
| 1233 | def check_setdefault(self, klass, key, value1, value2): |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1234 | self.assertIsNot(value1, value2, |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 1235 | "invalid test" |
| 1236 | " -- value parameters must be distinct objects") |
| 1237 | weakdict = klass() |
| 1238 | o = weakdict.setdefault(key, value1) |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 1239 | self.assertIs(o, value1) |
| 1240 | self.assertIn(key, weakdict) |
| 1241 | self.assertIs(weakdict.get(key), value1) |
| 1242 | self.assertIs(weakdict[key], value1) |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 1243 | |
| 1244 | o = weakdict.setdefault(key, value2) |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 1245 | self.assertIs(o, value1) |
| 1246 | self.assertIn(key, weakdict) |
| 1247 | self.assertIs(weakdict.get(key), value1) |
| 1248 | self.assertIs(weakdict[key], value1) |
Fred Drake | aaa48ff | 2001-05-10 17:16:38 +0000 | [diff] [blame] | 1249 | |
| 1250 | def test_weak_valued_dict_setdefault(self): |
| 1251 | self.check_setdefault(weakref.WeakValueDictionary, |
| 1252 | "key", C(), C()) |
| 1253 | |
| 1254 | def test_weak_keyed_dict_setdefault(self): |
| 1255 | self.check_setdefault(weakref.WeakKeyDictionary, |
| 1256 | C(), "value 1", "value 2") |
| 1257 | |
Fred Drake | a0a4ab1 | 2001-04-16 17:37:27 +0000 | [diff] [blame] | 1258 | def check_update(self, klass, dict): |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 1259 | # |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 1260 | # This exercises d.update(), len(d), d.keys(), in d, |
Fred Drake | 0e540c3 | 2001-05-02 05:44:22 +0000 | [diff] [blame] | 1261 | # d.get(), d[]. |
| 1262 | # |
Fred Drake | a0a4ab1 | 2001-04-16 17:37:27 +0000 | [diff] [blame] | 1263 | weakdict = klass() |
| 1264 | weakdict.update(dict) |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 1265 | self.assertEqual(len(weakdict), len(dict)) |
Fred Drake | a0a4ab1 | 2001-04-16 17:37:27 +0000 | [diff] [blame] | 1266 | for k in weakdict.keys(): |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 1267 | self.assertIn(k, dict, |
Fred Drake | a0a4ab1 | 2001-04-16 17:37:27 +0000 | [diff] [blame] | 1268 | "mysterious new key appeared in weak dict") |
| 1269 | v = dict.get(k) |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 1270 | self.assertIs(v, weakdict[k]) |
| 1271 | self.assertIs(v, weakdict.get(k)) |
Fred Drake | a0a4ab1 | 2001-04-16 17:37:27 +0000 | [diff] [blame] | 1272 | for k in dict.keys(): |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 1273 | self.assertIn(k, weakdict, |
Fred Drake | a0a4ab1 | 2001-04-16 17:37:27 +0000 | [diff] [blame] | 1274 | "original key disappeared in weak dict") |
| 1275 | v = dict[k] |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 1276 | self.assertIs(v, weakdict[k]) |
| 1277 | self.assertIs(v, weakdict.get(k)) |
Fred Drake | a0a4ab1 | 2001-04-16 17:37:27 +0000 | [diff] [blame] | 1278 | |
| 1279 | def test_weak_valued_dict_update(self): |
| 1280 | self.check_update(weakref.WeakValueDictionary, |
| 1281 | {1: C(), 'a': C(), C(): C()}) |
| 1282 | |
| 1283 | def test_weak_keyed_dict_update(self): |
| 1284 | self.check_update(weakref.WeakKeyDictionary, |
| 1285 | {C(): 1, C(): 2, C(): 3}) |
| 1286 | |
Fred Drake | ccc7562 | 2001-09-06 14:52:39 +0000 | [diff] [blame] | 1287 | def test_weak_keyed_delitem(self): |
| 1288 | d = weakref.WeakKeyDictionary() |
| 1289 | o1 = Object('1') |
| 1290 | o2 = Object('2') |
| 1291 | d[o1] = 'something' |
| 1292 | d[o2] = 'something' |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1293 | self.assertEqual(len(d), 2) |
Fred Drake | ccc7562 | 2001-09-06 14:52:39 +0000 | [diff] [blame] | 1294 | del d[o1] |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1295 | self.assertEqual(len(d), 1) |
| 1296 | self.assertEqual(d.keys(), [o2]) |
Fred Drake | ccc7562 | 2001-09-06 14:52:39 +0000 | [diff] [blame] | 1297 | |
| 1298 | def test_weak_valued_delitem(self): |
| 1299 | d = weakref.WeakValueDictionary() |
| 1300 | o1 = Object('1') |
| 1301 | o2 = Object('2') |
| 1302 | d['something'] = o1 |
| 1303 | d['something else'] = o2 |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1304 | self.assertEqual(len(d), 2) |
Fred Drake | ccc7562 | 2001-09-06 14:52:39 +0000 | [diff] [blame] | 1305 | del d['something'] |
Serhiy Storchaka | ca626b1 | 2013-11-17 13:20:50 +0200 | [diff] [blame] | 1306 | self.assertEqual(len(d), 1) |
| 1307 | self.assertEqual(d.items(), [('something else', o2)]) |
Fred Drake | ccc7562 | 2001-09-06 14:52:39 +0000 | [diff] [blame] | 1308 | |
Tim Peters | 886128f | 2003-05-25 01:45:11 +0000 | [diff] [blame] | 1309 | def test_weak_keyed_bad_delitem(self): |
| 1310 | d = weakref.WeakKeyDictionary() |
| 1311 | o = Object('1') |
| 1312 | # An attempt to delete an object that isn't there should raise |
Tim Peters | 50d8b8b | 2003-05-25 17:44:31 +0000 | [diff] [blame] | 1313 | # KeyError. It didn't before 2.3. |
Tim Peters | 886128f | 2003-05-25 01:45:11 +0000 | [diff] [blame] | 1314 | self.assertRaises(KeyError, d.__delitem__, o) |
Tim Peters | 50d8b8b | 2003-05-25 17:44:31 +0000 | [diff] [blame] | 1315 | self.assertRaises(KeyError, d.__getitem__, o) |
| 1316 | |
| 1317 | # If a key isn't of a weakly referencable type, __getitem__ and |
| 1318 | # __setitem__ raise TypeError. __delitem__ should too. |
| 1319 | self.assertRaises(TypeError, d.__delitem__, 13) |
| 1320 | self.assertRaises(TypeError, d.__getitem__, 13) |
| 1321 | self.assertRaises(TypeError, d.__setitem__, 13, 13) |
Tim Peters | 886128f | 2003-05-25 01:45:11 +0000 | [diff] [blame] | 1322 | |
| 1323 | def test_weak_keyed_cascading_deletes(self): |
| 1324 | # SF bug 742860. For some reason, before 2.3 __delitem__ iterated |
| 1325 | # over the keys via self.data.iterkeys(). If things vanished from |
| 1326 | # the dict during this (or got added), that caused a RuntimeError. |
| 1327 | |
| 1328 | d = weakref.WeakKeyDictionary() |
| 1329 | mutate = False |
| 1330 | |
| 1331 | class C(object): |
| 1332 | def __init__(self, i): |
| 1333 | self.value = i |
| 1334 | def __hash__(self): |
| 1335 | return hash(self.value) |
| 1336 | def __eq__(self, other): |
| 1337 | if mutate: |
| 1338 | # Side effect that mutates the dict, by removing the |
| 1339 | # last strong reference to a key. |
| 1340 | del objs[-1] |
| 1341 | return self.value == other.value |
| 1342 | |
| 1343 | objs = [C(i) for i in range(4)] |
| 1344 | for o in objs: |
| 1345 | d[o] = o.value |
| 1346 | del o # now the only strong references to keys are in objs |
| 1347 | # Find the order in which iterkeys sees the keys. |
| 1348 | objs = d.keys() |
| 1349 | # Reverse it, so that the iteration implementation of __delitem__ |
| 1350 | # has to keep looping to find the first object we delete. |
| 1351 | objs.reverse() |
Tim Peters | 50d8b8b | 2003-05-25 17:44:31 +0000 | [diff] [blame] | 1352 | |
Tim Peters | 886128f | 2003-05-25 01:45:11 +0000 | [diff] [blame] | 1353 | # Turn on mutation in C.__eq__. The first time thru the loop, |
| 1354 | # under the iterkeys() business the first comparison will delete |
| 1355 | # the last item iterkeys() would see, and that causes a |
| 1356 | # RuntimeError: dictionary changed size during iteration |
| 1357 | # when the iterkeys() loop goes around to try comparing the next |
Tim Peters | 50d8b8b | 2003-05-25 17:44:31 +0000 | [diff] [blame] | 1358 | # key. After this was fixed, it just deletes the last object *our* |
Tim Peters | 886128f | 2003-05-25 01:45:11 +0000 | [diff] [blame] | 1359 | # "for o in obj" loop would have gotten to. |
| 1360 | mutate = True |
| 1361 | count = 0 |
| 1362 | for o in objs: |
| 1363 | count += 1 |
| 1364 | del d[o] |
| 1365 | self.assertEqual(len(d), 0) |
| 1366 | self.assertEqual(count, 2) |
| 1367 | |
Walter Dörwald | 0a6d0ff | 2004-05-31 16:29:04 +0000 | [diff] [blame] | 1368 | from test import mapping_tests |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 1369 | |
Walter Dörwald | 0a6d0ff | 2004-05-31 16:29:04 +0000 | [diff] [blame] | 1370 | class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol): |
Fred Drake | f425b1e | 2003-07-14 21:37:17 +0000 | [diff] [blame] | 1371 | """Check that WeakValueDictionary conforms to the mapping protocol""" |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 1372 | __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)} |
Walter Dörwald | 118f931 | 2004-06-02 18:42:25 +0000 | [diff] [blame] | 1373 | type2test = weakref.WeakValueDictionary |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 1374 | def _reference(self): |
| 1375 | return self.__ref.copy() |
| 1376 | |
Walter Dörwald | 0a6d0ff | 2004-05-31 16:29:04 +0000 | [diff] [blame] | 1377 | class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol): |
Fred Drake | f425b1e | 2003-07-14 21:37:17 +0000 | [diff] [blame] | 1378 | """Check that WeakKeyDictionary conforms to the mapping protocol""" |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 1379 | __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3} |
Walter Dörwald | 118f931 | 2004-06-02 18:42:25 +0000 | [diff] [blame] | 1380 | type2test = weakref.WeakKeyDictionary |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 1381 | def _reference(self): |
| 1382 | return self.__ref.copy() |
Martin v. Löwis | 5e16333 | 2001-02-27 18:36:56 +0000 | [diff] [blame] | 1383 | |
Georg Brandl | 88659b0 | 2008-05-20 08:40:43 +0000 | [diff] [blame] | 1384 | libreftest = """ Doctest for examples in the library reference: weakref.rst |
Georg Brandl | 9a65d58 | 2005-07-02 19:07:30 +0000 | [diff] [blame] | 1385 | |
| 1386 | >>> import weakref |
| 1387 | >>> class Dict(dict): |
| 1388 | ... pass |
| 1389 | ... |
| 1390 | >>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable |
| 1391 | >>> r = weakref.ref(obj) |
Armin Rigo | a3f0927 | 2006-05-28 19:13:17 +0000 | [diff] [blame] | 1392 | >>> print r() is obj |
| 1393 | True |
Georg Brandl | 9a65d58 | 2005-07-02 19:07:30 +0000 | [diff] [blame] | 1394 | |
| 1395 | >>> import weakref |
| 1396 | >>> class Object: |
| 1397 | ... pass |
| 1398 | ... |
| 1399 | >>> o = Object() |
| 1400 | >>> r = weakref.ref(o) |
| 1401 | >>> o2 = r() |
| 1402 | >>> o is o2 |
| 1403 | True |
| 1404 | >>> del o, o2 |
| 1405 | >>> print r() |
| 1406 | None |
| 1407 | |
| 1408 | >>> import weakref |
| 1409 | >>> class ExtendedRef(weakref.ref): |
| 1410 | ... def __init__(self, ob, callback=None, **annotations): |
| 1411 | ... super(ExtendedRef, self).__init__(ob, callback) |
| 1412 | ... self.__counter = 0 |
| 1413 | ... for k, v in annotations.iteritems(): |
| 1414 | ... setattr(self, k, v) |
| 1415 | ... def __call__(self): |
| 1416 | ... '''Return a pair containing the referent and the number of |
| 1417 | ... times the reference has been called. |
| 1418 | ... ''' |
| 1419 | ... ob = super(ExtendedRef, self).__call__() |
| 1420 | ... if ob is not None: |
| 1421 | ... self.__counter += 1 |
| 1422 | ... ob = (ob, self.__counter) |
| 1423 | ... return ob |
| 1424 | ... |
| 1425 | >>> class A: # not in docs from here, just testing the ExtendedRef |
| 1426 | ... pass |
| 1427 | ... |
| 1428 | >>> a = A() |
| 1429 | >>> r = ExtendedRef(a, foo=1, bar="baz") |
| 1430 | >>> r.foo |
| 1431 | 1 |
| 1432 | >>> r.bar |
| 1433 | 'baz' |
| 1434 | >>> r()[1] |
| 1435 | 1 |
| 1436 | >>> r()[1] |
| 1437 | 2 |
| 1438 | >>> r()[0] is a |
| 1439 | True |
| 1440 | |
| 1441 | |
| 1442 | >>> import weakref |
| 1443 | >>> _id2obj_dict = weakref.WeakValueDictionary() |
| 1444 | >>> def remember(obj): |
| 1445 | ... oid = id(obj) |
| 1446 | ... _id2obj_dict[oid] = obj |
| 1447 | ... return oid |
| 1448 | ... |
| 1449 | >>> def id2obj(oid): |
| 1450 | ... return _id2obj_dict[oid] |
| 1451 | ... |
| 1452 | >>> a = A() # from here, just testing |
| 1453 | >>> a_id = remember(a) |
| 1454 | >>> id2obj(a_id) is a |
| 1455 | True |
| 1456 | >>> del a |
| 1457 | >>> try: |
| 1458 | ... id2obj(a_id) |
| 1459 | ... except KeyError: |
| 1460 | ... print 'OK' |
| 1461 | ... else: |
| 1462 | ... print 'WeakValueDictionary error' |
| 1463 | OK |
| 1464 | |
| 1465 | """ |
| 1466 | |
| 1467 | __test__ = {'libreftest' : libreftest} |
| 1468 | |
Fred Drake | 2e2be37 | 2001-09-20 21:33:42 +0000 | [diff] [blame] | 1469 | def test_main(): |
Walter Dörwald | 21d3a32 | 2003-05-01 17:45:56 +0000 | [diff] [blame] | 1470 | test_support.run_unittest( |
| 1471 | ReferencesTestCase, |
| 1472 | MappingTestCase, |
| 1473 | WeakValueDictionaryTestCase, |
Fred Drake | f425b1e | 2003-07-14 21:37:17 +0000 | [diff] [blame] | 1474 | WeakKeyDictionaryTestCase, |
Amaury Forgeot d'Arc | a8919fe | 2008-06-16 19:12:42 +0000 | [diff] [blame] | 1475 | SubclassableWeakrefTestCase, |
Fred Drake | f425b1e | 2003-07-14 21:37:17 +0000 | [diff] [blame] | 1476 | ) |
Georg Brandl | 9a65d58 | 2005-07-02 19:07:30 +0000 | [diff] [blame] | 1477 | test_support.run_doctest(sys.modules[__name__]) |
Fred Drake | 2e2be37 | 2001-09-20 21:33:42 +0000 | [diff] [blame] | 1478 | |
| 1479 | |
| 1480 | if __name__ == "__main__": |
| 1481 | test_main() |