"""Weak reference support for Python.This module is an implementation of PEP 205:http://www.python.org/dev/peps/pep-0205/"""# Naming convention: Variables named "wr" are weak reference objects;# they are called this instead of "ref" to avoid name collisions with# the module-global ref() function imported from _weakref.importUserDictfrom_weakrefimport(getweakrefcount,getweakrefs,ref,proxy,CallableProxyType,ProxyType,ReferenceType)from_weakrefsetimportWeakSetfromexceptionsimportReferenceErrorProxyTypes=(ProxyType,CallableProxyType)__all__=["ref","proxy","getweakrefcount","getweakrefs","WeakKeyDictionary","ReferenceError","ReferenceType","ProxyType","CallableProxyType","ProxyTypes","WeakValueDictionary",'WeakSet']classWeakValueDictionary(UserDict.UserDict):"""Mapping class that references values weakly. Entries in the dictionary will be discarded when no strong reference to the value exists anymore """# We inherit the constructor without worrying about the input# dictionary; since it uses our .update() method, we get the right# checks (if the other dictionary is a WeakValueDictionary,# objects are unwrapped on the way out, and we always wrap on the# way in).def__init__(self,*args,**kw):defremove(wr,selfref=ref(self)):self=selfref()ifselfisnotNone:delself.data[wr.key]self._remove=removeUserDict.UserDict.__init__(self,*args,**kw)def__getitem__(self,key):o=self.data[key]()ifoisNone:raiseKeyError,keyelse:returnodef__contains__(self,key):try:o=self.data[key]()exceptKeyError:returnFalsereturnoisnotNonedefhas_key(self,key):try:o=self.data[key]()exceptKeyError:returnFalsereturnoisnotNonedef__repr__(self):return"<WeakValueDictionary at %s>"%id(self)def__setitem__(self,key,value):self.data[key]=KeyedRef(value,self._remove,key)defcopy(self):new=WeakValueDictionary()forkey,wrinself.data.items():o=wr()ifoisnotNone:new[key]=oreturnnew__copy__=copydef__deepcopy__(self,memo):fromcopyimportdeepcopynew=self.__class__()forkey,wrinself.data.items():o=wr()ifoisnotNone:new[deepcopy(key,memo)]=oreturnnewdefget(self,key,default=None):try:wr=self.data[key]exceptKeyError:returndefaultelse:o=wr()ifoisNone:# This should only happenreturndefaultelse:returnodefitems(self):L=[]forkey,wrinself.data.items():o=wr()ifoisnotNone:L.append((key,o))returnLdefiteritems(self):forwrinself.data.itervalues():value=wr()ifvalueisnotNone:yieldwr.key,valuedefiterkeys(self):returnself.data.iterkeys()def__iter__(self):returnself.data.iterkeys()defitervaluerefs(self):"""Return an iterator that yields the weak references to the values. The references are not guaranteed to be 'live' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to keep the values around longer than needed. """returnself.data.itervalues()defitervalues(self):forwrinself.data.itervalues():obj=wr()ifobjisnotNone:yieldobjdefpopitem(self):while1:key,wr=self.data.popitem()o=wr()ifoisnotNone:returnkey,odefpop(self,key,*args):try:o=self.data.pop(key)()exceptKeyError:ifargs:returnargs[0]raiseifoisNone:raiseKeyError,keyelse:returnodefsetdefault(self,key,default=None):try:wr=self.data[key]exceptKeyError:self.data[key]=KeyedRef(default,self._remove,key)returndefaultelse:returnwr()defupdate(self,dict=None,**kwargs):d=self.dataifdictisnotNone:ifnothasattr(dict,"items"):dict=type({})(dict)forkey,oindict.items():d[key]=KeyedRef(o,self._remove,key)iflen(kwargs):self.update(kwargs)defvaluerefs(self):"""Return a list of weak references to the values. The references are not guaranteed to be 'live' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to keep the values around longer than needed. """returnself.data.values()defvalues(self):L=[]forwrinself.data.values():o=wr()ifoisnotNone:L.append(o)returnLclassKeyedRef(ref):"""Specialized reference that includes a key corresponding to the value. This is used in the WeakValueDictionary to avoid having to create a function object for each key stored in the mapping. A shared callback object can use the 'key' attribute of a KeyedRef instead of getting a reference to the key from an enclosing scope. """__slots__="key",def__new__(type,ob,callback,key):self=ref.__new__(type,ob,callback)self.key=keyreturnselfdef__init__(self,ob,callback,key):super(KeyedRef,self).__init__(ob,callback)classWeakKeyDictionary(UserDict.UserDict):""" Mapping class that references keys weakly. Entries in the dictionary will be discarded when there is no longer a strong reference to the key. This can be used to associate additional data with an object owned by other parts of an application without adding attributes to those objects. This can be especially useful with objects that override attribute accesses. """def__init__(self,dict=None):self.data={}defremove(k,selfref=ref(self)):self=selfref()ifselfisnotNone:delself.data[k]self._remove=removeifdictisnotNone:self.update(dict)def__delitem__(self,key):delself.data[ref(key)]def__getitem__(self,key):returnself.data[ref(key)]def__repr__(self):return"<WeakKeyDictionary at %s>"%id(self)def__setitem__(self,key,value):self.data[ref(key,self._remove)]=valuedefcopy(self):new=WeakKeyDictionary()forkey,valueinself.data.items():o=key()ifoisnotNone:new[o]=valuereturnnew__copy__=copydef__deepcopy__(self,memo):fromcopyimportdeepcopynew=self.__class__()forkey,valueinself.data.items():o=key()ifoisnotNone:new[o]=deepcopy(value,memo)returnnewdefget(self,key,default=None):returnself.data.get(ref(key),default)defhas_key(self,key):try:wr=ref(key)exceptTypeError:return0returnwrinself.datadef__contains__(self,key):try:wr=ref(key)exceptTypeError:return0returnwrinself.datadefitems(self):L=[]forkey,valueinself.data.items():o=key()ifoisnotNone:L.append((o,value))returnLdefiteritems(self):forwr,valueinself.data.iteritems():key=wr()ifkeyisnotNone:yieldkey,valuedefiterkeyrefs(self):"""Return an iterator that yields the weak references to the keys. The references are not guaranteed to be 'live' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to keep the keys around longer than needed. """returnself.data.iterkeys()defiterkeys(self):forwrinself.data.iterkeys():obj=wr()ifobjisnotNone:yieldobjdef__iter__(self):returnself.iterkeys()defitervalues(self):returnself.data.itervalues()defkeyrefs(self):"""Return a list of weak references to the keys. The references are not guaranteed to be 'live' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to keep the keys around longer than needed. """returnself.data.keys()defkeys(self):L=[]forwrinself.data.keys():o=wr()ifoisnotNone:L.append(o)returnLdefpopitem(self):while1:key,value=self.data.popitem()o=key()ifoisnotNone:returno,valuedefpop(self,key,*args):returnself.data.pop(ref(key),*args)defsetdefault(self,key,default=None):returnself.data.setdefault(ref(key,self._remove),default)defupdate(self,dict=None,**kwargs):d=self.dataifdictisnotNone:ifnothasattr(dict,"items"):dict=type({})(dict)forkey,valueindict.items():d[ref(key,self._remove)]=valueiflen(kwargs):self.update(kwargs)