weak reference callback

Christian Heimes lists at cheimes.de
Sat Aug 29 17:14:17 EDT 2009


Paul Pogonyshev wrote:
> 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")

Yes, you'll definitely see a RuntimeError because you forgot to declare
callback_called as a global variable. :)

Christian



More information about the Python-list mailing list