[Tutor] Python Extensions in C

Alan Gauld alan.gauld at btinternet.com
Thu May 26 19:24:48 CEST 2011

"James Reynolds" <eire1130 at gmail.com> wrote

> I was wondering if you all could look over my code and give some 
> feedback.
> Here is the link for the code: http://pastebin.com/jw3ihfsN

Some style issues, the indentation is inconsistent. Also
the braces positioning is one of the worst for comprehension
(See the book Code Complete for better styles!)

Lots of little issues.
You need to be more careful on error checking than in Python,.

For example consider what happens in avg_func() if count is zero.
Also what happens in the loop if a is greater than count?
Also, can PyFloat_AsDouble fail? If so what does temp become?
And what does that do to sumall? (I don't know the answers BTW
so don't read too much into these questions. They are just
examples of the pathalogical approach you need to take
when writing C!)

I don't know how the Python libraries handle memory but there
seems to be implicit memory allocation taking place but no
deallocation. I assume DECREF actually does more than
decrements the refernce count but actually deallocates the
memory when it gets to zero?

Finally, always, always check pointers passed as parameters
before use. Trying to use a NULL pointer is probably the
number one source of errors in production C code. A case
where you don't is in avg_func(). It may be OK and seq
is being set by


but the fact it says ...GET_ITEM suggests to me that it
probably isn't and expects a valid object reference.

Just some thoughts based on a very quick read. And
my C is very rusty, I haven't written any real C for at least
10 years!


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list