[Python-Dev] Weakref design questions

Brian Quinlan brian@sweetapp.com
Fri, 18 Oct 2002 19:51:18 -0700


David Abrahams:
> > So I proxy the bound methods and kill them when p dies.

> I don't quite understand what "proxy the bound methods" means.

Most extension types have a function like this:

PyObject *
MyObject_getattr(MyObject*    self, 
                 char *       name)
{    
	/* check for attributes */
	...

      /* ok, not an attribute, now check the methods
	return Py_FindMethod(
            MyObject_methods, 
            (PyObject *) self, 
            name);
}

Py_FindMethod() returns a PyCFunctionObject. The PyCFunctionObject will
own a reference to the MyObject "self". 

Since "self" has a limited lifetime this would be bad. So we could do
this:

PyObject *
MyObject_getattr(MyObject*    self, 
                 char *       name)
{    
	/* check for attributes */
	...

      /* ok, not an attribute, now check the methods
	method = Py_FindMethod(
            MyObject_methods, 
            (PyObject *) self, 
            name);

	if (method != NULL) {
		add_to_list_of_objects_to_kill(method)
		return PyWeakref_NewProxy(method);
	}

	return NULL;
}

But we can't quite do this because builtin functions are not proxyable.

> So you want a weakrefref. Well, I think this problem can be solved 
> by applying the Fundamental Theorem of Software Engineering: apply 
> an extra level of indirection. 

That's what I do. I was just wondering if there is any reason not to
make C functions weakref/proxyable.

> But Guido's approach of having the wrapper methods check for a null
DOM*
> seems like a reasonable one to me. 

It's not unreasonable and it is a bit simpler. But it is more work and
reduces performance slightly in the case where no check need be
performed i.e. the object is owned by Python.

> That's clear to me now. Very interesting thread; thanks for posting 
> it here!

Yeah, my first non-stupid post to python-dev.

Cheers,
Brian