Defining Python class methods in C

Alex Martelli aleax at
Sat Mar 22 09:47:10 CET 2003

<posted & mailed>

Bryan wrote:

> can someone please help me with this?
> there is this cookbook recipe that shows how to make a class type in
> c.
> what this recipe doesn't show is exactly how to instantiate one of
> these objects in c (not python) and call the __init__ method.
> obviously you first call initFoo(), but then what? does anyone know
> how to do this?

Whoa there -- initFoo gets called on your behalf from Python when
you *IMPORT* module foo!

You're trying to do in C the exact equivalent of Python code:

    import Foo
    aninst = Foo.Foo()

and that's all -- calling __init__ is another task performed by
Python on your behalf when you call the class!

Very well, so that's exactly what your C code has to do, no
more, no less: import module Foo, get its Foo attribute (a
class), call it and keep the result -- period.  E.g. (with
declaration at use, as in C++ rather than C, for clarity):

PyObject *fooModule = PyImport_ImportModule("Foo");
if(!fooModule) return NULL;    // propagate exception if any
PyObject *fooClass = PyObject_GetAttrString(fooModule, "Foo");
if(!fooClass) return NULL;     // propagate exception if any
PyObject *fooInstance = PyObject_CallObject(fooClass, NULL);
if(!fooInstance) return NULL;  // propagate exception if any

this needs a few enhancements (you should e.g. decref the
class object before propagating the exception if calling
it fails, to avoid any memory leaks -- you should generally
use PyImport_Import() rather than the simpler variant
PyImport_ImportModule() to ensure you go through any import
hooks that may be installed -- etc, etc) but I'm trying to
focus on communicating the key idea -- that you're basically
coding Python in C via C/API calls.

It makes no difference whether module Foo and its attributes
are implemented in Python or in C -- use the same approach!


More information about the Python-list mailing list