weak reference callback

P

Paul Pogonyshev

Hi,

Is weak reference callback called immediately after the referenced
object is deleted or at arbitrary point in time after that? I.e. is
it possible to see a dead reference before the callback is called?

More formally, will this ever raise?

callback_called = False
def note_deletion (ref):
callback_called = True

x = ...
ref = weakref.ref (x, note_deletion)

...

if ref () is None and not callback_called:
raise RuntimeError ("reference is dead, yet callback hasn't been called yet")

Paul
 
L

larudwer

Paul Pogonyshev said:
Hi,

Is weak reference callback called immediately after the referenced
object is deleted or at arbitrary point in time after that? I.e. is
it possible to see a dead reference before the callback is called?

More formally, will this ever raise?

callback_called = False
def note_deletion (ref):
callback_called = True
ref = weakref.ref (x, note_deletion)
if ref () is None and not callback_called:
raise RuntimeError ("reference is dead, yet callback hasn't been
called yet")

The Manual says:
"If callback is provided and not None, 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."

This says that the Object is deleted first, and the callback functions will
be called after that. Since after 'after that' IS an arbitrary point in
time your example SHOULD raise.

I think it is save to assume that this will never raise in an single
threaded cpython application because the GIL and reference counting scheme
etc. will prevent this.

However, this is an implementation specific detail of the cpython runtime
and it is not save to rely on this behavior.
It may be completely different in an multi threaded environment or any other
implementation of Python.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top