User guide
NumPy User Guide, Release 1.9.0
You should be able to run this command assuming your search-path is set-up properly. This command will produce an
extension module named addmodule.c in the current directory. This extension module can now be compiled and used
from Python just like any other extension module.
Creating a compiled extension module
You can also get f2py to compile add.f and also compile its produced extension module leaving only a shared-library
extension file that can be imported from Python:
f2py -c -m add add.f
This command leaves a file named add.{ext} in the current directory (where {ext} is the appropriate extension for a
python extension module on your platform — so, pyd, etc. ). This module may then be imported from Python. It
will contain a method for each subroutine in add (zadd, cadd, dadd, sadd). The docstring of each method contains
information about how the module method may be called:
>>> import add
>>> print add.zadd.__doc__
zadd - Function signature:
zadd(a,b,c,n)
Required arguments:
a : input rank-1 array(’D’) with bounds (
*
)
b : input rank-1 array(’D’) with bounds (
*
)
c : input rank-1 array(’D’) with bounds (
*
)
n : input int
Improving the basic interface
The default interface is a very literal translation of the fortran code into Python. The Fortran array arguments must now
be NumPy arrays and the integer argument should be an integer. The interface will attempt to convert all arguments
to their required types (and shapes) and issue an error if unsuccessful. However, because it knows nothing about the
semantics of the arguments (such that C is an output and n should really match the array sizes), it is possible to abuse
this function in ways that can cause Python to crash. For example:
>>> add.zadd([1,2,3],[1,2],[3,4],1000)
will cause a program crash on most systems. Under the covers, the lists are being converted to proper arrays but then
the underlying add loop is told to cycle way beyond the borders of the allocated memory.
In order to improve the interface, directives should be provided. This is accomplished by constructing an interface
definition file. It is usually best to start from the interface file that f2py can produce (where it gets its default behavior
from). To get f2py to generate the interface file use the -h option:
f2py -h add.pyf -m add add.f
This command leaves the file add.pyf in the current directory. The section of this file corresponding to zadd is:
subroutine zadd(a,b,c,n) ! in :add:add.f
double complex dimension(
*
) :: a
double complex dimension(
*
) :: b
double complex dimension(
*
) :: c
integer :: n
end subroutine zadd
By placing intent directives and checking code, the interface can be cleaned up quite a bit until the Python module
method is both easier to use and more robust.
5.2. Using Python as glue 63