f2py example import Fortran library from Python

f2py uses Fortran code from Python.

f2py_demo.py calls the Fortran code fortprod.f.

f2py requires Fortran Intent()

We run fairly large complicated Fortran codebases from Python with f2py. The only modification you have to do to Fortran code to work with f2py is at the subroutine you want to call from Python, add Intent() for each variable. If you feel uneasy modifying the source code, you can put a comment like

!f2py Intent(in) :: x

You don’t have to put those comments if you’re modifying the code to add intent(). If using intent(out), be sure the variable is always initialized for all cases in the subroutine. Otherwise you may get 0 or an unpredictable result in return (this is true for plain standalone Fortran, too).

f2py currently assumes intent(in) for all variables, which clearly won’t work for many use cases. Plain Fortran defaults to intent(inout). However, with f2py the intent(inout) will return None unless the inout variable is a Numpy  ndarray. Scalar inout will be left unmodified. It’s OK to have the Fortran code expecting a scalar with a 0d ndarray inout.