extension: how to implement module function, object method

Harald Kirsch kirschh at lionbioscience.com
Tue May 8 04:48:52 EDT 2001


I want to implement an extension in C such that object methods called
like e.g.

  thing.do(otherThing)

can also be called as module funtions like

  modulename.do(thing, otherThing)

I looked into the implementation of string in the 2.0 code and found
that only the object method is actually implemented in C while the
module function is python code like this:

  def string.join(words, sep = ' '):
    return sep.join(words)

Can anyone tell me why it is not done in C along the lines of the
following example code fragment? Depeding on the first argument being
NULL the function behaves like a simple function or like an object
method. 

static PyObject*
someObjectMethod(PyObject* self, PyObject *args)
{
  int i;

  if( !self ) {
    /* we were in fact called as a module function, try to retrieve
       a matching object from args */
    if( !PyArg_ParseTuple(args, "o!i", SomeObjectType, &self, &i) ) 
      return NULL;
  } else {
    /* we were obviously called as an object method so args should
       only have the int value. */
    if( !PyArg_ParseTuple(args, "i", &i) ) 
      return NULL;
  }
}

Thanks,
  Harald Kirsch

-- 
----------------+------------------------------------------------------
Harald Kirsch   | kirschh at lionbioscience.com | "How old is the epsilon?"
LION bioscience | +49 6221 4038 172          |        -- Paul Erdös
       *** Please do not send me copies of your posts. ***



More information about the Python-list mailing list