Python C module questions

Robert Kern rkern at
Thu Sep 1 20:37:34 CEST 2005

jeremy.d.brewer at wrote:
> Hi,
> I'm rather new to Python, and I've just written my first Python C
> module.  I was wondering if some more experience Pythonista would look
> over what I've written and given me some pointers (or find some bugs).
> I had a few questions while writing this as well.
> Also, I know that there are much better ways to compute nearest
> neighbors than the brute force n^2 method, but this is plenty fast for
> this application (at least the C version is).
> 1.  How do I add docstrings to my module?

You mean a docstring on the module object itself? In initmodule() make a
string object with the contents of the docstring and assign it to
module.__doc__ . There might be a more idiomatic way, but I can't think
of it without trawling through the docs.

> 2.  The Python reference counting and memory managment seemes awfully
> repetetive and error prone.  Is there a nicer way of doing this?  I
> know there are some wrappers out there such as Pyrex and SWIG that
> might prove useful.

I'm quite a fan of Pyrex. You may also want to give ctypes a shot. SWIG
doesn't help as much with the reference counting

> 3.  This module consisted of turning 4 Python sequences into C double
> arrays, performing some calculations, and then turning a C int array
> into a Python tuple for return.  And it was a lot of work.  Are there
> any nice wrapper functions out there for turning Python sequences into
> C arrays and vice versa?

> Thanks,
> Jeremy Brewer
> The code is below:

You probably shouldn't post such large pieces of code to the list.

Robert Kern
rkern at

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

More information about the Python-list mailing list