[Python-Dev] Weak references: dereference notification

Guido van Rossum guido at python.org
Wed Nov 9 18:23:34 CET 2005


> > Gustavo J. A. M. Carneiro wrote:
> > >   I have come across a situation where I find the current weak
> > > references interface for extension types insufficient.
> > >
> > >   Currently you only have a tp_weaklistoffset slot, pointing to a
> > > PyObject with weak references.  However, in my case[1] I _really_ need
> > > to be notified when a weak reference is dereferenced.

I find reading through the bug discussion a bit difficult to
understand your use case. Could you explain it here? If you can't
explain it you certainly won't get your problem solved! :-)

> > > What happens now
> > > is that, when you call a weakref object, a simple Py_INCREF is done on
> > > the referenced object.  It would be easy to implement a new slot to
> > > contain a function that should be called when a weak reference is
> > > dereferenced.  Or, alternatively, a slot or class attribute that
> > > indicates an alternative type that should be used to create weak
> > > references: instead of the builtin weakref object, a subtype of it, so
> > > you can override tp_call.
> > >
> > >   Does this sounds acceptable?

[Jim Fulton]
> > Since you can now (as of 2.4) subclass the weakref.ref class, you should be able to
> > do this yourself in Python.  See for example, weakref.KeyedRef.
>
>  I know I can subclass it, but it doesn't change anything.  If people
> keep writing code like weakref.ref(myobj) instead of myweakref(myobj),
> it still won't work.
>
>   I wouldn't want to have to teach users of the library that they need
> to use an alternative type; that seldom doesn't work.
>
>   Now, if there was a place in the type that contained information like
>
>         "for creating weak references of instances of this type, use this
> weakref class"
>
> and weakref.ref was smart enough to lookup this type and use it, only
> _then_ it could work.

Looks what you're looking for is a customizable factory fuction.

--
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list