Wrap Fortran into Python with f2py on Ubuntu: Full Guide

Overview

High-performance numerical computing often relies on legacy Fortran routines, but orchestrating workflows in Python offers superior flexibility. The f2py tool bridges this gap seamlessly by generating binary wrappers around native Fortran code. This walk-through covers the complete lifecycle on Ubuntu: setting up the compiler toolchain, crafting Fortran 90 subroutines, extracting signatures, compiling dynamic shared objects, and validating execution directly inside Python scripts.

1. Setting Up the Toolchain and Compiler Packages

Before compiling native code, provision your Ubuntu workstation with the essential build utilities, Python development headers, and the GNU Fortran compiler.

Install build-essential, gfortran, and Python dependencies

Confirm that the system detects gfortran and inspect the active toolchain release.

Verify GNU Fortran compiler installation

Ensure the Python environment includes numpy, which supplies the underlying machinery for binding multi-dimensional arrays between C/Python and Fortran.

Inspect active NumPy installation version

Under the hood, f2py analyzes Fortran signatures and automates the creation of C-API glue code. Review the bundled numpy.f2py version to ensure CLI access is fully functional.

⚙️ [Key Parameters & Flags]

-c : Compiles Fortran source files directly into a loadable Python shared library (.so).
-m <module_name> : Sets the imported module identity for the generated extension.
-h <file.pyf> : Parses source routines and writes a Fortran signature template (.pyf).
--fcompiler=<compiler> : Forces a specific Fortran compiler family (e.g., gnu95, intel).
--f77flags="<options>" : Appends specialized optimization or syntax flags for F77 compilers.
--f90flags="<options>" : Supplies extra parameters to the modern F90 compiler backend.
--overwrite-signature : Forces regeneration of existing .pyf interface files without prompting.

Check numpy.f2py utility version

2. Implementing the Fortran Computational Subroutine

Create a dedicated workspace to house your source files and build artifacts:

Initialize demo workspace directory

Next, create math_ops.f90, which implements an element-wise vector summation. Notice the explicit intent(in) and intent(out) decorators: these annotations instruct f2py how to marshal input arguments and map return values back into standard Python returns.

Create Fortran 90 array addition routine

Confirm that the file was generated with appropriate user permissions and non-zero byte size.

Inspect created math_ops.f90 file metadata

3. Extracting the Interface Signature File (.pyf)

Navigate into the demonstration directory before triggering interface analysis:

Navigate to the project root

Rather than compiling blindly, parse the subroutine layout using -h to generate math_ops.pyf. This intermediate descriptor defines argument types, intent decorators, and array sizing rules.

Generate f2py wrapper signature definition

Review the resulting .pyf manifest to verify that argument shapes match expectations and that output buffers are appropriately flagged for automatic allocation.

Inspect generated math_ops.pyf contents

4. Building the Dynamic CPython Extension (.so)

Ensure the shell remains anchored in the working directory before invoking compilation:

Ensure current directory is f2py_demo

Pass both the signature definition math_ops.pyf and implementation math_ops.f90 to f2py using the -c flag. This command coordinates C wrapper generation, links against NumPy headers, and drives gfortran to produce a compiled binary.

Build compiled shared library module

Verify that the target .so shared library exists on disk with architecture and ABI tags matching your active Python runtime.

List compiled shared object binaries

5. Integrating and Validating Fortran Calls in Python

Switch to the project root to prepare the test suite:

Switch to f2py_demo directory

Write test_f2py.py to exercise the compiled module. Because the signature explicitly designated array c with intent(out), the Fortran subroutine behaves like a pure Python function, automatically returning the processed NumPy array.

Write verification script test_f2py.py

Execute the verification script to validate memory alignment, cross-language data interchange, and numerical precision.

Run Python script invoking compiled Fortran module

By integrating Fortran subroutines via f2py, you achieve the raw execution speeds of compiled numerical kernels while keeping application logic, data prep, and visualization firmly within Python’s productive ecosystem.