Search code examples
pythonglobal-variablesfortranf2py

How to deal with global variables when calling fortran code in python (e.g. with f2py)?


I want to run some fortran codes with python and am using f2py -c -m for it. However, it seems that only the FUNCTIONs are packed into the .so file, but not the PROGRAM. How can I deal with global variables then? For example, a variable c is put in a module

MODULE nfw
  double precision :: c
END MODULE nfw

,is modified in the PROGRAM, and is used by a FUNCTION in the same file implicitly

PROGRAM Compute_Profile
  USE nfw
  c = 5.0
END PROGRAM Compute_Profile

DOUBLE PRECISION FUNCTION y(x)
  USE nfw
  double precision :: x
  y = c * x
  return
END FUNCTION y

How can I call let the function y(x) know about the value of c in python?


Solution

  • Under your f2py module should be another module, the Fortran one named nfw. It should be there.

    $ f2py -c -m mod nfw.f90
    
    $ python
    import mod
    mod.nfw.c
    
    array(0.0)
    

    Make sure you compile the source file with the module with f2py.