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.

Test Function<br />

The one last thing we want to do is to add a test function. In fact, we already have one, in the form of<br />

the main() function. Now, it is potentially dangerous to have a main() function in our code because there<br />

should only be one main() in the system. We remove this danger by changing the name of our main() to<br />

test() and wrapping it, adding Extest_test() and updating the ExtestMethods array so that they both<br />

look like this:<br />

static PyObject *<br />

Extest_test(PyObject *self, PyObject *args) {<br />

test();<br />

return (PyObject*)Py_BuildValue("");<br />

}<br />

static PyMethodDef<br />

ExtestMethods[] = {<br />

{ "fac", Extest_fac, METH_VARARGS },<br />

{ "doppel", Extest_doppel, METH_VARARGS },<br />

{ "test", Extest_test, METH_VARARGS },<br />

{ NULL, NULL },<br />

};<br />

The Extest_test() module function just runs test() and returns an empty string, resulting in a <strong>Python</strong><br />

value of None being returned to the caller.<br />

Now we can run the same test from <strong>Python</strong>:<br />

>>> Extest.test()<br />

4! == 24<br />

8! == 40320<br />

12! == 479001600<br />

reversing 'abcdef', we get 'fedcba'<br />

reversing 'madam', we get 'madam'<br />

>>><br />

In Example 22.3, we present the final version of Extest2.c that was used to generate the output we just<br />

witnessed.<br />

Example 22.3. <strong>Python</strong>-Wrapped Version of C Library (Extest2.c)

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

Saved successfully!

Ooh no, something went wrong!