"""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.from_weakrefimport(getweakrefcount,getweakrefs,ref,proxy,CallableProxyType,ProxyType,ReferenceType)from_weakrefsetimportWeakSet,_IterationGuardimportcollections# Import after _weakref to avoid circular import.ProxyTypes=(ProxyType,CallableProxyType)__all__=["ref","proxy","getweakrefcount","getweakrefs","WeakKeyDictionary","ReferenceType","ProxyType","CallableProxyType","ProxyTypes","WeakValueDictionary","WeakSet"]classWeakValueDictionary(collections.MutableMapping):"""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:ifself._iterating:self._pending_removals.append(wr.key)else:delself.data[wr.key]self._remove=remove# A list of keys to be removedself._pending_removals=[]self._iterating=set()self.data=d={}self.update(*args,**kw)def_commit_removals(self):l=self._pending_removalsd=self.data# We shouldn't encounter any KeyError, because this method should# always be called *before* mutating the dict.whilel:deld[l.pop()]def__getitem__(self,key):o=self.data[key]()ifoisNone:raiseKeyError(key)else:returnodef__delitem__(self,key):ifself._pending_removals:self._commit_removals()delself.data[key]def__len__(self):returnsum(wr()isnotNoneforwrinself.data.values())def__contains__(self,key):try:o=self.data[key]()exceptKeyError:returnFalsereturnoisnotNonedef__repr__(self):return"<WeakValueDictionary at %s>"%id(self)def__setitem__(self,key,value):ifself._pending_removals:self._commit_removals()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):with_IterationGuard(self):fork,wrinself.data.items():v=wr()ifvisnotNone:yieldk,vdefkeys(self):with_IterationGuard(self):fork,wrinself.data.items():ifwr()isnotNone:yieldk__iter__=keysdefitervaluerefs(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. """with_IterationGuard(self):forwrinself.data.values():yieldwrdefvalues(self):with_IterationGuard(self):forwrinself.data.values():obj=wr()ifobjisnotNone:yieldobjdefpopitem(self):ifself._pending_removals:self._commit_removals()whileTrue:key,wr=self.data.popitem()o=wr()ifoisnotNone:returnkey,odefpop(self,key,*args):ifself._pending_removals:self._commit_removals()try:o=self.data.pop(key)()exceptKeyError:ifargs:returnargs[0]raiseifoisNone:raiseKeyError(key)else:returnodefsetdefault(self,key,default=None):try:wr=self.data[key]exceptKeyError:ifself._pending_removals:self._commit_removals()self.data[key]=KeyedRef(default,self._remove,key)returndefaultelse:returnwr()defupdate(self,dict=None,**kwargs):ifself._pending_removals:self._commit_removals()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. """returnlist(self.data.values())classKeyedRef(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().__init__(ob,callback)classWeakKeyDictionary(collections.MutableMapping):""" 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:ifself._iterating:self._pending_removals.append(k)else:delself.data[k]self._remove=remove# A list of dead weakrefs (keys to be removed)self._pending_removals=[]self._iterating=set()ifdictisnotNone:self.update(dict)def_commit_removals(self):# NOTE: We don't need to call this method before mutating the dict,# because a dead weakref never compares equal to a live weakref,# even if they happened to refer to equal objects.# However, it means keys may already have been removed.l=self._pending_removalsd=self.datawhilel:try:deld[l.pop()]exceptKeyError:passdef__delitem__(self,key):delself.data[ref(key)]def__getitem__(self,key):returnself.data[ref(key)]def__len__(self):returnlen(self.data)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)def__contains__(self,key):try:wr=ref(key)exceptTypeError:returnFalsereturnwrinself.datadefitems(self):with_IterationGuard(self):forwr,valueinself.data.items():key=wr()ifkeyisnotNone:yieldkey,valuedefkeys(self):with_IterationGuard(self):forwrinself.data:obj=wr()ifobjisnotNone:yieldobj__iter__=keysdefvalues(self):with_IterationGuard(self):forwr,valueinself.data.items():ifwr()isnotNone:yieldvaluedefkeyrefs(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. """returnlist(self.data)defpopitem(self):whileTrue: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)