15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

22.2. Extending <strong>Python</strong> by Writing Extensions<br />

Creating extensions for <strong>Python</strong> involves three main steps:<br />

1.<br />

2.<br />

3.<br />

Creating application code<br />

Wrapping code with boilerplates<br />

Compilation and testing<br />

In this section, we will break out all three pieces and expose them all to you.<br />

22.2.1. Create Your Application Code<br />

First, before any code becomes an extension, create a standalone "library." In other words, create your<br />

code keeping in mind that it is going to turn into a <strong>Python</strong> module. Design your functions and objects<br />

with the vision that <strong>Python</strong> code will be communicating and sharing data with your C code and vice<br />

versa.<br />

Next, create test code to bulletproof your software. You may even use the "<strong>Python</strong>ic" development<br />

method of designating your main() function in C as the testing application so that if your code is<br />

compiled, linked, and loaded into an executable (as opposed to just a shared object), invocation of such<br />

an executable will result in a regression test of your software library. For our extension example below,<br />

this is exactly what we do.<br />

The test case involves two C functions that we want to bring to the world of <strong>Python</strong> programming. The<br />

first is the recursive factorial function, fac(). The second, reverse(), is a simple string reverse<br />

algorithm, whose main purpose is to reverse a string "in place," that is, to return a string whose<br />

characters are all reversed from their original positions, all without allocating a separate string to copy in<br />

reverse order. Because this involves the use of pointers, we need to carefully design and debug our code<br />

before bringing <strong>Python</strong> into the picture.<br />

Our first version, Extest1.c, is presented in Example 22.1.<br />

This code consists of a pair of functions, fac() and reverse(), which are implementations of the<br />

functionality we described above. fac() takes a single integer argument and recursively calculates the<br />

result, which is eventually returned to the caller once it exits the outermost call.<br />

Example 22.1. Pure C Version of Library (Extest1.c)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!