[pypy-dev] [cpyext] how to make use of the weakref callback?

Stefan Behnel stefan_ml at behnel.de
Sun Oct 14 20:44:58 CEST 2012


Amaury Forgeot d'Arc, 14.10.2012 20:11:
> 2012/10/14 Stefan Behnel:
>> when creating a new weakref using PyWeakref_NewRef(obj, callback), a Python
>> callback function can be registered that is supposed to get called when the
>> weakly referenced object dies. The callback receives a single argument, the
>> weakref object.
>>
>> Now, the weak reference object itself is mostly useless, what is
>> interesting is the object it originally referenced. I tried getting at that
>> object by calling PyWeakref_LockObject(), but that already returns None at
>> that point. PyWeakref_GetObject() is basically just a wrapper around that
>> function and behaves the same.
>>
>> Is there any way to figure out what that object was that has just died when
>> the callback gets called?
> 
> I don't think so:
> http://docs.python.org/library/weakref.html#weakref.ref
> """the weak reference object will be passed as the only parameter to
> the callback; the referent will no longer be available."""

Ah, right, thanks! I see it now, CPython behaves the same way in its
weakrefobject.c. It clears the references before calling the callbacks. How
very unfortunate.

Guess I'll have to see if a closure is worth the hassle for me (I only care
about C pointer fields of the object).

Stefan




More information about the pypy-dev mailing list