Gfort2py v2.0.0 release

After many years (and several complete re-writes) I am pleased to announce the release gfort2py v2.0.0. gfort2py is a Python library enabling the calling of Fortran code from Python. The main aim of this library is to make calling the Fortran code as easy as possible by minimising the number of changes to the Fortran code. All that is required is to have your code in a module and compiled as a shared library. No annotations or other changes needed.

Source code is available at GitHub - rjfarmer/gfort2py: Library to allow calling fortran code from python

Gfort2py works with python >=3.7 and gfortran >=8. Note that there are many API breakages with the gfort2py 1.. series. Please refer to the README at gfort2py/ at main · rjfarmer/gfort2py · GitHub for examples of the new features.

Gfort2py supports many modern (and old) Fortran features including:

Scalars (ints, reals, logicals, characters)
Arrays of (ints, reals, logicals, characters): explicit, assumed shape, assumed size, and allocatable arrays.
Derived types including scalars and arrays.
Explicit arrays of derived types (assumed shape are not yet supported)
Allocatable strings (partial support)
Calling functions and subroutines.

More features are planned to be added over time.

Installation via pip:
python -m pip install --upgrade gfort2py

For those that want to get involved: Improvements to the test suite to include untested or new Fortran features (and Python code to test those features, even if it doesn’t yet work) is the most helpful. Otherwise, bug reports on broken features are also helpful.


Thanks for the project. The GitHub page gives instructions for Linux and MacOS, but It works on Windows, too. I downloaded the project to c:\fortran\public_domain\github\gfort2py,
where I created stats.f90

module stats_mod
implicit none
integer, parameter :: dp = kind(1.0d0)
function range_vec(x) result(xrange)
real(kind=dp), intent(in) :: x(:)
real(kind=dp)             :: xrange
if (size(x) > 0) then
   xrange = maxval(x) - minval(x)
   xrange = 0.0_dp
end if
end function range_vec
end module stats_mod

and created a DLL with gfortran -shared -o libfile.dll stats.f90. Then running the Python code

import numpy as np
import gfort2py as gf


vec = np.random.normal(size=4)
print("vec =", vec)
res = x.range_vec(vec)
print("argument(s) passed:", res[1])
print("range from Fortran, NumPy =", res[0], np.max(vec) - np.min(vec))


vec = [-0.0860823   1.15058585 -0.08149836  1.07459795]
argument(s) passed: {'x': array([-0.0860823 ,  1.15058585, -0.08149836,  1.07459795])}
range from Fortran, NumPy = 1.2366681428133555 1.2366681428133555

Thanks for testing I updated the docs to add Windows compile options.

1 Like

Great work! I’m particularly happy to see that it supports assumed shape arrays, because I don’t know how to do it with ctypes.