Class
persistent.wref.WeakRef

Persistent weak references

Persistent weak references are used much like Python weak references. The major difference is that you can't specify an object to be called when the object is removed from the database.

Here's an example. We'll start by creating a persistent object and a refernce to it:

>>> import persistent.list >>> import ZODB.tests.util >>> ob = persistent.list.PersistentList() >>> ref = WeakRef(ob) >>> ref() is ob True

The hash of the ref if the same as the hash of the referenced object:

>>> hash(ref) == hash(ob) True

Two refs to the same object are equal:

>>> WeakRef(ob) == ref True

>>> ob2 = persistent.list.PersistentList([1]) >>> WeakRef(ob2) == ref False

Lets save the reference and the referenced object in a database:

>>> db = ZODB.tests.util.DB()

>>> conn1 = db.open() >>> conn1.root()['ob'] = ob >>> conn1.root()['ref'] = ref >>> ZODB.tests.util.commit()

If we open a new connection, we can use the reference:

>>> conn2 = db.open() >>> conn2.root()['ref']() is conn2.root()['ob'] True >>> hash(conn2.root()['ref']) == hash(conn2.root()['ob']) True

But if we delete the referenced object and pack:

>>> del conn2.root()['ob'] >>> ZODB.tests.util.commit() >>> ZODB.tests.util.pack(db)

And then look in a new connection:

>>> conn3 = db.open() >>> conn3.root()['ob'] Traceback (most recent call last): ... KeyError: ob

Trying to dereference the reference returns None:

>>> conn3.root()['ref']()

Trying to get a hash, raises a type error:

>>> hash(conn3.root()['ref']) Traceback (most recent call last): ... TypeError: Weakly-referenced object has gone away

Always explicitly close databases: :)

>>> db.close()

Base classes

Implemented Interfaces

There are no implemented interfaces.

Attributes/Properties

There are no attributes in this class.

Methods

There are no methods in this class.

Known Subclasses

There are no known subclasses.