Registering C methods when writing a C extension type?

Tom Epperly tepperly at llnl.gov
Thu Jan 4 10:52:17 EST 2001


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.

Alex Martelli wrote:
[ several lines deleted]
> > I am wondering what the relative merits/penalties of doing something
> > like the following in the constructor for the hypothetical myobject
> > instead of the above. I would like feedback about issues of style (am
> > I violating the designers intent or using functions intended for
> > internal use only), forward/backward portability, and efficiency.
> 
> I fail to see any advantage of the following approach.  OTOH, the
> disadvantages are pretty obvious:
> 
> 
> > static myobject *
> > new_myobject()
> > {
> >   myobject *self;
> >   const int len = sizeof(object_methods)/sizeof(PyMethodDef);
> >   int i;
> >   self = PyObject_NEW(myobject, &myobjecttype);
> >   if (self == NULL) return NULL;
> >   for(i = 0 ; i < len ; i++){
> >     PyObject *func = PyCFunction_New(object_methods + i, self);
> >     if (func != NULL) {
> >       PyObject_SetAttrString(self, object_methods[i].ml_name,func);
> >       Py_DECREF(func); /* remove extra reference */
> >     }
> >   }
> >   return self;
> > }
> > ...each new-object instancing pays a time price to initialize the
> > table of its methods, and, perhaps more important, the *space* to hold
> > a table that's just a copy of the object_methods one to all intents
> > and purposes.  What's the point...?

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.
2. Avoid creating a PyCFunction_New once per method call.

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

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:

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);
}

Tom

--
------------------------------------------------------------------------
Tom Epperly
Center for Applied Scientific Computing   Phone: 925-424-3159
Lawrence Livermore National Laboratory      Fax: 925-424-2477
L-661, P.O. Box 808, Livermore, CA 94551  Email: tepperly at llnl.gov
------------------------------------------------------------------------





More information about the Python-list mailing list