Converting Python code to Fortran code

Can we convert Python code to Fortran code. If yes how?

Please guide me I will be very thankful

It depends.

You have some options:

  • rewrite everything line by line (very time-consuming, especially if your Python code uses many libraries)
  • identify the bottlenecks of your code and only convert them to Fortran
    • one way to do this is to compile a Fortran module to be usable by Python (f2py3)
    • or you can use libraries, which already use C or Fortran, for example SciPy or NumPy

If your code uses NumPy arrays, you should be able to translate it easily to Fortran, because the NumPy syntax is heavily based on Fortran array operations.


As said already, if your code uses array operations, try changing that part to Fortran.
Also, If you want to change the whole python code (if it is not time-consuming and worth the effort), try to develop a similarity between the python and Fortran statements. To start with try this website to have a comparison between Fortran and python (Python Fortran Rosetta Stone — Fortran90 1.0 documentation). I personally find this comparison very useful.

bests of luck!!

1 Like

My list of Fortran tools has a section on Translation to Fortran, where pyccel is mentioned. The Readme says

Pyccel stands for Python extension language using accelerators.

The aim of Pyccel is to provide a simple way to generate automatically, parallel low level code. The main uses would be:

  1. Convert a Python code (or project) into a Fortran or C code.
  2. Accelerate Python functions by converting them to Fortran or C functions.

Pyccel can be viewed as:

  • Python-to-Fortran/C converter
  • a compiler for a Domain Specific Language with Python syntax

Pyccel comes with a selection of extensions allowing you to convert calls to some specific python packages to Fortran/C. The following packages will be covered (partially):

  • numpy
  • scipy
  • mpi4py (not available yet)
  • h5py (not available yet)

Pyccel’s acceleration capabilities lead to much faster code. A small speed comparison of python vs pyccel or other tools can be found in the performance file.

I wrote about it in a December 2020 thread Translating Python to Fortran with pyccel – it has become more capable since then. Pyccel is an active project with numerous contributors. It would be great if translation to Fortran became a standard way of speeding up Python code, especially scientific code. If many Fortranners tried it and gave feedback to the Pyccel developers, that would benefit both the scientific Python and Fortran communities. They were responsive to a few issues I raised.