User guide
NumPy User Guide, Release 1.9.0
subroutine zadd(a,b,c,n) ! in :add:add.f
double complex dimension(n) :: a
double complex dimension(n) :: b
double complex intent(out),dimension(n) :: c
integer intent(hide),depend(a) :: n=len(a)
end subroutine zadd
The intent directive, intent(out) is used to tell f2py that c is an output variable and should be created by the interface
before being passed to the underlying code. The intent(hide) directive tells f2py to not allow the user to specify the
variable, n, but instead to get it from the size of a. The depend( a ) directive is necessary to tell f2py that the value of
n depends on the input a (so that it won’t try to create the variable n until the variable a is created).
The new interface has docstring:
>>> print add.zadd.__doc__
zadd - Function signature:
c = zadd(a,b)
Required arguments:
a : input rank-1 array(’D’) with bounds (n)
b : input rank-1 array(’D’) with bounds (n)
Return objects:
c : rank-1 array(’D’) with bounds (n)
Now, the function can be called in a much more robust way:
>>> add.zadd([1,2,3],[4,5,6])
array([ 5.+0.j, 7.+0.j, 9.+0.j])
Notice the automatic conversion to the correct format that occurred.
Inserting directives in Fortran source
The nice interface can also be generated automatically by placing the variable directives as special comments in the
original fortran code. Thus, if I modify the source code to contain:
C
SUBROUTINE ZADD(A,B,C,N)
C
CF2PY INTENT(OUT) :: C
CF2PY INTENT(HIDE) :: N
CF2PY DOUBLE COMPLEX :: A(N)
CF2PY DOUBLE COMPLEX :: B(N)
CF2PY DOUBLE COMPLEX :: C(N)
DOUBLE COMPLEX A(
*
)
DOUBLE COMPLEX B(
*
)
DOUBLE COMPLEX C(
*
)
INTEGER N
DO 20 J = 1, N
C(J) = A(J) + B(J)
20 CONTINUE
END
Then, I can compile the extension module using:
f2py -c -m add add.f
The resulting signature for the function add.zadd is exactly the same one that was created previously. If the original
source code had contained A(N) instead of A(*) and so forth with B and C, then I could obtain (nearly) the same
64 Chapter 5. Using Numpy C-API