Skip to content

Instantly share code, notes, and snippets.

@krystophny
Created January 10, 2025 07:33
Show Gist options
  • Save krystophny/7a0e15050b3575dbac2054af62e7fccb to your computer and use it in GitHub Desktop.
Save krystophny/7a0e15050b3575dbac2054af62e7fccb to your computer and use it in GitHub Desktop.
setup.py for f2py with legacy support
from setuptools import Extension, setup
from setuptools.command.build_ext import build_ext
from importlib.machinery import EXTENSION_SUFFIXES
import os
import shutil
import sys
import subprocess
import sysconfig
class F2PyExtension(Extension):
def __init__(self, name, fortran_sources, **kwargs):
super().__init__(name, sources=[], **kwargs)
self.fortran_sources = fortran_sources
class BuildF2PyExtension(build_ext):
def build_extension(self, ext):
output_module = ext.name
env = os.environ.copy()
if sys.version_info < (3, 12):
env["SETUPTOOLS_USE_DISTUTILS"] = "1"
subprocess.check_call([
"f2py", "-c", "-m", output_module, *ext.fortran_sources
], env=env)
ext_suffix = sysconfig.get_config_var("EXT_SUFFIX")
lib_name = f"{output_module}{ext_suffix}"
ext_path = self.get_ext_fullpath(ext.name)
ext_dir = os.path.dirname(ext_path)
if not os.path.exists(ext_dir):
os.makedirs(ext_dir)
shutil.move(lib_name, ext_path)
ext = F2PyExtension('my_ext',
fortran_sources=['source1.f90',
'source2.f90'])
setup(
ext_modules=[ext],
cmdclass={'build_ext': BuildF2PyExtension},
)
@joshuashaffer
Copy link

Thank you for this simple environment variable fix. It's mind-boggling that these so-called professionals just tell you to 'stop doing things the old way.'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment