User guide

NumPy User Guide, Release 1.9.0
PyInline
This is a much older module that allows automatic building of extension modules so that C-code can be included with
Python code. It’s latest release (version 0.03) was in 2001, and it appears that it is not being updated.
PyFort
PyFort is a nice tool for wrapping Fortran and Fortran-like C-code into Python with support for Numeric arrays. It
was written by Paul Dubois, a distinguished computer scientist and the very first maintainer of Numeric (now retired).
It is worth mentioning in the hopes that somebody will update PyFort to work with NumPy arrays as well which now
support either Fortran or C-style contiguous arrays.
5.3 Writing your own ufunc
I have the Power!
He-Man
5.3.1 Creating a new universal function
Before reading this, it may help to familiarize yourself with the basics of C extensions for Python by reading/skimming
the tutorials in Section 1 of Extending and Embedding the Python Interpreter and in How to extend Numpy
The umath module is a computer-generated C-module that creates many ufuncs. It provides a great many examples of
how to create a universal function. Creating your own ufunc that will make use of the ufunc machinery is not difficult
either. Suppose you have a function that you want to operate element-by-element over its inputs. By creating a new
ufunc you will obtain a function that handles
broadcasting
N-dimensional looping
automatic type-conversions with minimal memory usage
optional output arrays
It is not difficult to create your own ufunc. All that is required is a 1-d loop for each data-type you want to support.
Each 1-d loop must have a specific signature, and only ufuncs for fixed-size data-types can be used. The function call
used to create a new ufunc to work on built-in data-types is given below. A different mechanism is used to register
ufuncs for user-defined data-types.
In the next several sections we give example code that can be easily modified to create your own ufuncs. The exam-
ples are successively more complete or complicated versions of the logit function, a common function in statistical
modeling. Logit is also interesting because, due to the magic of IEEE standards (specifically IEEE 754), all of the
logit functions created below automatically have the following behavior.
>>> logit(0)
-inf
>>> logit(1)
inf
>>> logit(2)
nan
>>> logit(-2)
nan
This is wonderful because the function writer doesn’t have to manually propagate infs or nans.
80 Chapter 5. Using Numpy C-API