-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_weakref.py
54 lines (33 loc) · 995 Bytes
/
test_weakref.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import weakref
def test_lifespan_of_weak_referenced_object():
context = Context()
place_foo_in(context)
assert context[0] is not None
# now make ref to be weak
context = WeakContext()
place_foo_in(context)
# assert context[0] is not None # oops!
assert context[0] is None
class Context(object):
def __init__(self):
self._context = list()
def append(self, object_):
self._context.append(object_)
def __getitem__(self, index):
return self._context[index]
def place_foo_in(context):
# create ref
foo = Foo()
context.append(foo)
# returning from function, there is another ref to `foo`,
# and it can not be freed yet
pass
class Foo(object):
pass
class WeakContext(object):
def __init__(self):
self._context = list()
def append(self, object_):
self._context.append(weakref.ref(object_))
def __getitem__(self, index):
return self._context[index]()