{ } Raw JSON

bundles / numpy 2.4.4 / docs

Doc

Boilerplate reduction and templating

docs/f2py:advanced:boilerplating

Using FYPP for binding generic interfaces

f2py doesn't currently support binding interface blocks. However, there are workarounds in use. Perhaps the best known is the usage of tempita for using .pyf.src files as is done in the bindings which are part of scipy. tempita support has been removed and is no longer recommended in any case.

Here we will discuss a few techniques to leverage f2py in conjunction with fypp to emulate generic interfaces and to ease the binding of multiple (similar) functions.

Basic example: Addition module

Let us build on the example (from the user guide, f2py-examples) of a subroutine which takes in two arrays and returns its sum.

We will recast this into modern fortran:

We could go on as in the original example, adding intents by hand among other things, however in production often there are other concerns. For one, we can template via FYPP the construction of similar functions:

This can be pre-processed to generate the full fortran code:

❯ fypp gen_adder.f90.fypp > adder.f90

As to be expected, this can be wrapped by f2py subsequently.

Now we will consider maintaining the bindings in a separate file. Note the following basic .pyf which can be generated for a single subroutine via f2py -m adder adder_base.f90 -h adder.pyf:

With the docstring:

Which is already pretty good. However, n should never be passed in the first place so we will make some minor adjustments.

Which corresponds to:

Finally, we can template over this in a similar manner, to attain the original goal of having bindings which make use of f2py directives and have minimal spurious repetition.

Usage boils down to:

fypp gen_adder.f90.fypp > adder.f90
fypp adder.pyf.fypp > adder.pyf
f2py -m adder -c adder.pyf adder.f90 --backend meson