Movatterモバイル変換


[0]ホーム

URL:


Up one LevelPython Library ReferenceContentsModule IndexIndex

5.11weakref -- Weak references

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.

class ref(object[, callback])
Return a weak reference toobject. The original object can be retrieved by calling the reference object if the referent is still alive; if the referent is no longer alive, calling the reference object will causeNone to be returned. Ifcallback is provided and notNone, and the returned weakref object is still alive, the callback will be called when the object is about to be finalized; the weak reference object will be passed as the only parameter to the callback; the referent will no longer be available.

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.

proxy(object[, callback])
Return a proxy toobject which uses a weak reference. This supports use of the proxy in most contexts instead of requiring the explicit dereferencing used with weak reference objects. The returned object will have a type of eitherProxyType 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.

getweakrefcount(object)
Return the number of weak references and proxies which refer toobject.

getweakrefs(object)
Return a list of all weak reference and proxy objects which refer toobject.

class WeakKeyDictionary([dict])
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.

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.

iterkeyrefs()
Return an iterator that yields the weak references to the keys.New in version 2.5.

keyrefs()
Return a list of weak references to the keys.New in version 2.5.

class WeakValueDictionary([dict])
Mapping class that references values weakly. Entries in the dictionary will be discarded when no strong reference to the value exists any more.

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.

itervaluerefs()
Return an iterator that yields the weak references to the values.New in version 2.5.

valuerefs()
Return a list of weak references to the values.New in version 2.5.

ReferenceType
The type object for weak references objects.

ProxyType
The type object for proxies of objects which are not callable.

CallableProxyType
The type object for proxies of callable objects.

ProxyTypes
Sequence containing all the type objects for proxies. This can make it simpler to test if an object is a proxy without being dependent on naming both proxy types.

exception ReferenceError
Exception raised when a proxy object is used but the underlying object has been collected. This is the same as the standardReferenceError exception.

See Also:

PEP 0205,Weak References
The proposal and rationale for this feature, including links to earlier implementations and information about similar features in other languages.



Subsections


Up one LevelPython Library ReferenceContentsModule IndexIndex

Release 2.5.2, documentation updated on 21st February, 2008.
SeeAbout this document... for information on suggesting changes.
[8]ページ先頭

©2009-2025 Movatter.jp