In this page, you can find a full description and a few examples of common usage
patterns for F2PY with Python and different argument types. For more examples
and use cases, see F2PY examples.
Fortran type objects
All wrappers for Fortran/C routines, common blocks, or Fortran 90 module data
generated by F2PY are exposed to Python as fortran type objects. Routine
wrappers are callable fortran type objects while wrappers to Fortran data
have attributes referring to data objects.
All fortran type objects have an attribute _cpointer that contains a
PyCapsule referring to the C pointer of the corresponding Fortran/C function
or variable at the C level. Such objects can be used as callback
arguments for F2PY generated functions to bypass the Python C/API layer for
calling Python functions from Fortran or C. This can be useful when the
computational aspects of such functions are implemented in C or Fortran and
wrapped with F2PY (or any other tool capable of providing the
containing a function).
In general, a scalar argument for a F2PY generated wrapper function can be an
ordinary Python scalar (integer, float, complex number) as well as an arbitrary
sequence object (list, tuple, array, string) of scalars. In the latter case, the
first element of the sequence object is passed to the Fortran routine as a
scalar argument.
Consider the following Fortran 77 code:
CFILE:SCALAR.FSUBROUTINE FOO(A,B)REAL*8A,BCf2pyintent(in)aCf2pyintent(inout)bPRINT*," A=",A," B=",BPRINT*,"INCREMENT A AND B"A=A+1D0B=B+1D0PRINT*,"NEW A=",A," B=",BENDCEND OFFILE SCALAR.F
and wrap it using f2py-c-mscalarscalar.f.
In Python:
>>> importscalar>>> print(scalar.foo.__doc__)foo(a,b)Wrapper for ``foo``.Parameters----------a : input floatb : in/output rank-0 array(float,'d')>>> scalar.foo(2,3) A= 2. B= 3. INCREMENT A AND B NEW A= 3. B= 4.>>> importnumpy>>>
String arguments
F2PY generated wrapper functions accept almost any Python object as a string
argument, since str is applied for non-string objects. Exceptions are NumPy
arrays that must have type code 'S1' or 'b' (corresponding to the
outdated 'c' or '1' typecodes, respectively) when used as string
arguments. See Scalars for more information on these typecodes.
A string can have an arbitrary length when used as a string argument for an F2PY
generated wrapper function. If the length is greater than expected, the string
is truncated silently. If the length is smaller than expected, additional memory
is allocated and filled with \0.
Because Python strings are immutable, an intent(inout) argument expects an
array version of a string in order to have in situ changes be effective.
In general, array arguments for F2PY generated wrapper functions accept
arbitrary sequences that can be transformed to NumPy array objects. There are
two notable exceptions:
intent(inout) array arguments must always be
proper-contiguous and have a compatible dtype,
otherwise an exception is raised.
intent(inplace) array arguments must be arrays. If these have
incompatible order or size, a converted copy is passed in, which is
copied back into the original array on exit (see the intent(inplace)attribute for more information).
In general, if a NumPy array is proper-contiguous and has
a proper type then it is directly passed to the wrapped Fortran/C function.
Otherwise, an element-wise copy of the input array is made and the copy, being
proper-contiguous and with proper type, is used as the array argument.
Usually there is no need to worry about how the arrays are stored in memory and
whether the wrapped functions, being either Fortran or C functions, assume one
or another storage order. F2PY automatically ensures that wrapped functions get
arguments with the proper storage order; the underlying algorithm is designed to
make copies of arrays only when absolutely necessary. However, when dealing with
very large multidimensional input arrays with sizes close to the size of the
physical memory in your computer, then care must be taken to ensure the usage of
proper-contiguous and proper type arguments.
To transform input arrays to column major storage order before passing
them to Fortran routines, use the function numpy.asfortranarray.
Consider the following Fortran 77 code:
CFILE:ARRAY.FSUBROUTINE FOO(A,N,M)CCINCREMENTTHEFIRSTROWAND DECREMENTTHEFIRSTCOLUMNOFACINTEGER N
and wrap it using f2py-c-marrarray.f-DF2PY_REPORT_ON_ARRAY_COPY=1.
In Python:
>>> importarr>>> fromnumpyimportasfortranarray>>> print(arr.foo.__doc__)a = foo(a,[overwrite_a])Wrapper for ``foo``.Parameters----------a : input rank-2 array('d') with bounds (n,m)Other Parameters----------------overwrite_a : input int, optional Default: 0Returns-------a : rank-2 array('d') with bounds (n,m)>>> a=
Call-back arguments
F2PY supports calling Python functions from Fortran or C codes.
>>> importcallback>>> print(callback.foo.__doc__)r = foo(fun,[fun_extra_args])Wrapper for ``foo``.Parameters----------fun : call-back functionOther Parameters----------------fun_extra_args : input tuple, optional Default: ()Returns-------r : floatNotes-----Call-back functions:: def fun(i): return r Required arguments: i : input int Return objects: r : float>>>
In the above example F2PY was able to guess accurately the signature
of the call-back function. However, sometimes F2PY cannot establish the
appropriate signature; in these cases the signature of the call-back
function must be explicitly defined in the signature file.
To facilitate this, signature files may contain special modules (the names of
these modules contain the special __user__ sub-string) that define the
various signatures for call-back functions. Callback arguments in routine
signatures have the external attribute (see also the intent(callback)attribute). To relate a callback argument with its
signature in a __user__ module block, a use statement can be utilized as
illustrated below. The same signature for a callback argument can be referred to
in different routine signatures.
We use the same Fortran 77 code as in the previous example but now
we will pretend that F2PY was not able to guess the signatures of
call-back arguments correctly. First, we create an initial signature
file callback2.pyf using F2PY:
f2py-mcallback2-hcallback2.pyfcallback.f
Then modify it as follows
! -*- f90 -*-
python module __user__routines
interface
function fun(i) result (r)
integer :: i
real*8 :: r
end function fun
end interface
end python module __user__routines
python module callback2
interface
subroutine foo(f,r)
use __user__routines, f=>fun
external f
real*8 intent(out) :: r
end subroutine foo
end interface
end python module callback2
Finally, we build the extension module using
f2py-ccallback2.pyfcallback.f.
An example Python session for this snippet would be identical to the previous
example except that the argument names would differ.
Sometimes a Fortran package may require that users provide routines that the
package will use. F2PY can construct an interface to such routines so that
Python functions can be called from Fortran.
Consider the following Fortran 77 subroutine that takes an array as its input
and applies a function func to its elements.
The Fortran code expects that the function func has been defined externally.
In order to use a Python function for func, it must have an attribute
intent(callback) and it must be specified before the external statement.
Finally, build an extension module using f2py-c-mfoocalculate.f
The function is included as an argument to the python function call to the
Fortran subroutine even though it was not in the Fortran subroutine argument
list. The “external” keyword refers to the C function generated by f2py, not the
Python function itself. The python function is essentially being supplied to the
C function.
The callback function may also be explicitly set in the module. Then it is not
necessary to pass the function in the argument list to the Fortran function.
This may be desired if the Fortran function calling the Python callback function
is itself called by another Fortran function.
>>> importpfromf>>> pfromf.f2()Traceback (most recent call last):
File "<stdin>", line 1, in <module>pfromf.error: Callback fpy not defined (as an argument or module pfromf attribute).>>> deff():print("python f")... >>> pfromf.fpy=f>>> pfromf.f2()
Resolving arguments to call-back functions
F2PY generated interfaces are very flexible with respect to call-back arguments. For each call-back argument an additional optional
argument <name>_extra_args is introduced by F2PY. This argument can be used
to pass extra arguments to user provided call-back functions.
If a F2PY generated wrapper function expects the following call-back argument:
deffun(a_1,...,a_n):...returnx_1,...,x_k
but the following Python function
Common blocks
F2PY generates wrappers to common blocks defined in a routine signature
block. Common blocks are visible to all Fortran codes linked to the current
extension module, but not to other extension modules (this restriction is due to
the way Python imports shared libraries). In Python, the F2PY wrappers to
common blocks are fortran type objects that have (dynamic) attributes
related to the data members of the common blocks. When accessed, these
attributes return as NumPy array objects (multidimensional arrays are
Fortran-contiguous) which directly link to data members in common blocks. Data
members can be changed by direct assignment or by in-place changes to the
corresponding array objects.
>>> importmoddata>>> print(moddata.mod.__doc__)i : 'i'-scalarx : 'i'-array(4)a : 'f'-array(2,3)b : 'f'-array(-1,-1), not allocatedfoo()Wrapper for ``foo``.>>> moddata.mod.i=5>>> moddata.mod.x[:2]=
Allocatable arrays
F2PY has basic support for Fortran 90 module allocatable arrays.
Consider the following Fortran 90 code:
module modreal,allocatable,dimension(:,:)::bcontains subroutine foointeger kif(allocated(b))then print*,"b=["do k=1,size(b,1)print*,b(k,1:size(b,2))enddo print*,"]"else print*,"b is not allocated"endif end subroutine fooend module mod
and wrap it using f2py-c-mallocarrallocarr.f90.
In Python:
>>> importallocarr>>> print(allocarr.mod.__doc__)b : 'f'-array(-1,-1), not allocatedfoo()Wrapper for ``foo``.>>> allocarr.mod.foo() b is not allocated>>> allocarr.mod.b=[[1,2,3
a
=
numpy
.
array
(
2
)
# these are integer rank-0 arrays
>>>
b
=
numpy
.
array
(
3
)
>>>
scalar
.
foo
(
a
,
b
)
A= 2. B= 3.
INCREMENT A AND B
NEW A= 3. B= 4.
>>>
print
(
a
,
b
)
# note that only b is changed in situ
2 4
Cf2py
intent
(
inout
)
b
,
d
PRINT
*
,
"A="
,
A
PRINT
*
,
"B="
,
B
PRINT
*
,
"C="
,
C
PRINT
*
,
"D="
,
D
PRINT
*
,
"CHANGE A,B,C,D"
A
(
1
:
1
)
=
'A'
B
(
1
:
1
)
=
'B'
C
(
1
:
1
)
=
'C'
D
(
1
:
1
)
=
'D'
PRINT
*
,
"A="
,
A
PRINT
*
,
"B="
,
B
PRINT
*
,
"C="
,
C
PRINT
*
,
"D="
,
D
END
C
END
OF
FILE
STRING
.
F
'
)
>>>
b
=
array
(
b
'123
\0\0
'
)
>>>
c
=
array
(
b
'123'
)
>>>
d
=
array
(
b
'123'
)
>>>
mystring
.
foo
(
a
,
b
,
c
,
d
)
A=123
B=123
C=123
D=123
CHANGE A,B,C,D
A=A23
B=B23
C=C23
D=D23
>>>
a
[()],
b
[()],
c
[()],
d
[()]
(b'123', b'B23', b'123', b'D2')
,
M
,
I
,
J
REAL
*
8
A
(
N
,
M
)
Cf2py
intent
(
in
,
out
,
copy
)
a
Cf2py
integer
intent
(
hide
),
depend
(
a
)
::
n
=
shape
(
a
,
0
),
m
=
shape
(
a
,
1
)
DO
J
=
1
,
M
A
(
1
,
J
)
=
A
(
1
,
J
)
+
1
D0
ENDDO
DO
I
=
1
,
N
A
(
I
,
1
)
=
A
(
I
,
1
)
-
1
D0
ENDDO
END
C
END
OF
FILE ARRAY
.
F
arr
.
foo
([[
1
,
2
,
3
],
...
[
4
,
5
,
6
]])
created an array from object
>>>
print
(
a
)
[[ 1. 3. 4.]
[ 3. 5. 6.]]
>>>
a
.
flags
.
c_contiguous
False
>>>
a
.
flags
.
f_contiguous
True
# even if a is proper-contiguous and has proper type,
# a copy is made forced by intent(copy) attribute
# to preserve its original contents
>>>
b
=
arr
.
foo
(
a
)
copied an array: size=6, elsize=8
>>>
print
(
a
)
[[ 1. 3. 4.]
[ 3. 5. 6.]]
>>>
print
(
b
)
[[ 1. 4. 5.]
[ 2. 5. 6.]]
>>>
b
=
arr
.
foo
(
a
,
overwrite_a
=
1
)
# a is passed directly to Fortran
...
# routine and its contents is discarded
...
>>>
print
(
a
)
[[ 1. 4. 5.]
[ 2. 5. 6.]]
>>>
print
(
b
)
[[ 1. 4. 5.]
[ 2. 5. 6.]]
>>>
a
is
b
# a and b are actually the same objects
True
>>>
print
(
arr
.
foo
([
1
,
2
,
3
]))
# different rank arrays are allowed
created an array from object
[ 1. 1. 2.]
>>>
print
(
arr
.
foo
([[[
1
],
[
2
],
[
3
]]]))
created an array from object
[[[ 1.]
[ 1.]
[ 2.]]]
>>>
>>>
# Creating arrays with column major data storage order:
...
>>>
s
=
asfortranarray
([[
1
,
2
,
3
],
[
4
,
5
,
6
]])
>>>
s
.
flags
.
f_contiguous
True
>>>
print
(
s
)
[[1 2 3]
[4 5 6]]
>>>
print
(
arr
.
foo
(
s
))
>>>
s2
=
asfortranarray
(
s
)
>>>
s2
is
s
# an array with column major storage order
# is returned immediately
True
>>>
# Note that arr.foo returns a column major data storage order array: