Registering C methods when writing a C extension type?

Alex Martelli aleaxit at yahoo.com
Thu Jan 4 12:55:23 EST 2001
"Tom Epperly" <tepperly at llnl.gov> wrote in message
news:mailman.978623584.28957.python-list at python.org...
> Thanks to everyone who replied. You helped clear up some of my
> misconceptions. I am fairly convinced by what I've read that what I've
> proposed is a bad idea.
    [snip]
> If I implement getattr/setattr with a PyDictObject (i.e. each myobject has
> a dictionary instance), I thought the potential benefits would be:
> 1. Replace the linear lookup time implicit in Py_FindMethod with nearly
>    constant time hash table lookup.

True.  But, how many methods will your objects have?  For a typical small
list, up to say 10-20, the small constants in the linear-time search may
still make it a win (or roughly a tie, turning into a win because of the
memory saving and speedier new-object generation).

> 2. Avoid creating a PyCFunction_New once per method call.

If a method is called in a tight loop, so that this is a worry, a
speedier solution may be for the _Python_ side of things to do the
lookup just once, saving the resulting callable in a local variable.


> It would be nice if there were a Py_FindMethodSorted where it assumed that
> the PyMethodDef's were alphabetically sorted.

It might produce a small gain, yes (or a big one, if the methods
are REALLY many).  But if measurement proves that this does in
fact make a measurable difference in your case, it's not hard to
implement that yourself (and maybe post it as a patch to the
sourceforge site) based on C's bsearch, I guess.  (Wait until you
_have_ measured... intuition regarding performance is SO tricky!).


> I was also considering a way to have one extension type being able to wrap
> up numerous IDL types. The alternative is to do something like:

Why not have a Python-visible type per IDL type?  I fail to see
any cost in that.


> struct myobject {
>   PyObject_HEAD
>   const PyMethodDef *object_methods;
> }
>
> static PyObject *
> myobject_getattr(myobject *self, char *name) {
>  /* other stuff deleted */
>  return Py_FindMethod(self->object_methods, self, name);
> }

Yes, you could do that -- have objects of the same Python-visible
type implement different sets of methods.  But the benefit sort
of eludes me here (the cost is also pretty small of course).


Alex






More information about the Python-list mailing list