Defining Python class methods in C

John Machin sjmachin at lexicon.net
Sun Mar 23 03:26:12 EST 2003


On 22 Mar 2003 17:32:13 -0800, belred1 at yahoo.com (Bryan) wrote:

>i found one of my problems:
>

Your main problem is that you are mixing up CLASS and TYPE. They are
*NOT* the same thing. Their internal structures are different.
Historically, classes were defined in Python modules and types were
defined in C, either in the Python core, or in extension modules. Some
work has been done on unification so that they appear similar to the
casual user. 

The cookbook recipe shows the bare skeleton of how  to mimic a CLASS
in C. You asked how, in C, to import a module and get an instance of a
CLASS defined therein. Alex showed you how. As Alex said, what he told
you will work whether or not the imported module is written in Python
or faked up in C using the cookbook recipe.

However you have departed from the recipe and have defined a TYPE in
C:

static PyTypeObject context_type = {
	PyObject_HEAD_INIT(NULL)
	0,
	"Context",
etc

You *don't* need this.

If you were to post *all* your code (X) extension module mimicing a
class (Y) C program or  extension module that imports X (Z) the Python
module that contains the "def start(ctx):" stuff (W) the C or Python
code that calls Z.start() ... then we might be able to help a bit
more.

By the way, you may want to consider checking for errors after many of
your PyXXXXX() calls. Note that the recipe leaves this very important
aspect out. For example, inspection of the source for PyClass_New()
shows that  there are many circumstances under which it will set up an
exception and return NULL. Any PyXXXXX() which returns an object on
success will do this upon failure --- you need to test for this and
bail out. Error indication for other varieties: RTFM for each PyXXXX()
that you call.

Maybe you *do* need a type and not a class -- what exactly are you
trying to achieve? Why do you think it is necessary for your
application to (a) mimic a class in C (b) import the mimicing module
from C? This sounds like far too much complexity to me.






More information about the Python-list mailing list