Package paramiko :: Module resource
[frames] | no frames]

Source Code for Module paramiko.resource

 1  # Copyright (C) 2003-2007  Robey Pointer <robey@lag.net> 
 2  # 
 3  # This file is part of paramiko. 
 4  # 
 5  # Paramiko is free software; you can redistribute it and/or modify it under the 
 6  # terms of the GNU Lesser General Public License as published by the Free 
 7  # Software Foundation; either version 2.1 of the License, or (at your option) 
 8  # any later version. 
 9  # 
10  # Paramiko is distrubuted in the hope that it will be useful, but WITHOUT ANY 
11  # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 
12  # A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more 
13  # details. 
14  # 
15  # You should have received a copy of the GNU Lesser General Public License 
16  # along with Paramiko; if not, write to the Free Software Foundation, Inc., 
17  # 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA. 
18   
19  """ 
20  Resource manager. 
21  """ 
22   
23  import weakref 
24   
25   
26 -class ResourceManager (object):
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
43 - def __init__(self):
44 self._table = {}
45
46 - def register(self, obj, resource):
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 # keep the weakref in a table so it sticks around long enough to get 67 # its callback called. :) 68 self._table[id(resource)] = weakref.ref(obj, callback)
69 70 71 # singleton 72 ResourceManager = ResourceManager() 73