New in version 2.1.
Theweakref module allows the Python programmer to createweak references to objects.
In the following, the termreferent means theobject which is referred to by a weak reference.
A weak reference to an object is not enough to keep the object alive:when the only remaining references to a referent are weak references,garbage collection is free to destroy the referent and reuse its memoryfor something else. A primary use for weak references is to implementcaches or mappings holding large objects, where it's desired that alarge object not be kept alive solely because it appears in a cache ormapping. For example, if you have a number of large binary image objects,you may wish to associate a name with each. If you used a Pythondictionary to map names to images, or images to names, the image objectswould remain alive just because they appeared as values or keys in thedictionaries. TheWeakKeyDictionary andWeakValueDictionary classes supplied by theweakrefmodule are an alternative, using weak references to construct mappingsthat don't keep objects alive solely because they appear in the mappingobjects. If, for example, an image object is a value in aWeakValueDictionary, then when the last remainingreferences to that image object are the weak references held by weakmappings, garbage collection can reclaim the object, and its correspondingentries in weak mappings are simply deleted.
WeakKeyDictionary andWeakValueDictionary use weakreferences in their implementation, setting up callback functions onthe weak references that notify the weak dictionaries when a key or valuehas been reclaimed by garbage collection. Most programs should find thatusing one of these weak dictionary types is all they need - it'snot usually necessary to create your own weak references directly. Thelow-level machinery used by the weak dictionary implementations is exposedby theweakref module for the benefit of advanced uses.
Not all objects can be weakly referenced; those objects which caninclude class instances, functions written in Python (but not in C),methods (both bound and unbound), sets, frozensets, file objects,generators, type objects, DBcursor objects from thebsddb module,sockets, arrays, deques, and regular expression pattern objects.Changed in version 2.4:Added support for files, sockets, arrays, and patterns.
Several builtin types such aslist anddict do notdirectly support weak references but can add support through subclassing:
class Dict(dict): passobj = Dict(red=1, green=2, blue=3) # this object is weak referencable
Extension types can easily be made to support weak references; see``Weak Reference Support'' inExtending and Embedding the PythonInterpreter.
| object[, callback]) |
It is allowable for many weak references to be constructed for the same object. Callbacks registered for each weak reference will be called from the most recently registered callback to the oldest registered callback.
Exceptions raised by the callback will be noted on the standard error output, but cannot be propagated; they are handled in exactly the same way as exceptions raised from an object's__del__() method.
Weak references are hashable if theobject is hashable. They will maintain their hash value even after theobject was deleted. Ifhash() is called the first time only after theobject was deleted, the call will raiseTypeError.
Weak references support tests for equality, but not ordering. If the referents are still alive, two references have the same equality relationship as their referents (regardless of thecallback). If either referent has been deleted, the references are equal only if the reference objects are the same object.
Changed in version 2.4:This is now a subclassable type rather than a factory function; it derives fromobject.
| object[, callback]) |
ProxyType orCallableProxyType, depending on whetherobject is callable. Proxy objects are not hashable regardless of the referent; this avoids a number of problems related to their fundamentally mutable nature, and prevent their use as dictionary keys.callback is the same as the parameter of the same name to theref() function.| object) |
| object) |
| [dict]) |
Note:Caution: Because aWeakKeyDictionary is built on top of a Python dictionary, it must not change size when iterating over it. This can be difficult to ensure for aWeakKeyDictionary because actions performed by the program during iteration may cause items in the dictionary to vanish "by magic" (as a side effect of garbage collection).
WeakKeyDictionary objects have the following additionalmethods. These expose the internal references directly. Thereferences are not guaranteed to be ``live'' at the time they areused, so the result of calling the references needs to be checkedbefore being used. This can be used to avoid creating references thatwill cause the garbage collector to keep the keys around longer thanneeded.
| ) |
| ) |
| [dict]) |
Note:Caution: Because aWeakValueDictionary is built on top of a Python dictionary, it must not change size when iterating over it. This can be difficult to ensure for aWeakValueDictionary because actions performed by the program during iteration may cause items in the dictionary to vanish "by magic" (as a side effect of garbage collection).
WeakValueDictionary objects have the following additionalmethods. These method have the same issues as theiterkeyrefs() andkeyrefs() methods ofWeakKeyDictionary objects.
| ) |
| ) |
See Also: