1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 """
20 Resource manager.
21 """
22
23 import weakref
24
25
27 """
28 A registry of objects and resources that should be closed when those
29 objects are deleted.
30
31 This is meant to be a safer alternative to python's C{__del__} method,
32 which can cause reference cycles to never be collected. Objects registered
33 with the ResourceManager can be collected but still free resources when
34 they die.
35
36 Resources are registered using L{register}, and when an object is garbage
37 collected, each registered resource is closed by having its C{close()}
38 method called. Multiple resources may be registered per object, but a
39 resource will only be closed once, even if multiple objects register it.
40 (The last object to register it wins.)
41 """
42
45
47 """
48 Register a resource to be closed with an object is collected.
49
50 When the given C{obj} is garbage-collected by the python interpreter,
51 the C{resource} will be closed by having its C{close()} method called.
52 Any exceptions are ignored.
53
54 @param obj: the object to track
55 @type obj: object
56 @param resource: the resource to close when the object is collected
57 @type resource: object
58 """
59 def callback(ref):
60 try:
61 resource.close()
62 except:
63 pass
64 del self._table[id(resource)]
65
66
67
68 self._table[id(resource)] = weakref.ref(obj, callback)
69
70
71
72 ResourceManager = ResourceManager()
73