Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to document fortran function for f2py?

I would like to use docstring or something similar to document my fortran routines which can be usable with the python help command. The autogenerated docstring made by f2py is very not sufficient and I need to add more details in the same way we do with the python function docstring.

In my idea, it should look like :

mymod.f :

subroutine foo()
! This is my function
end subroutine

and in a python session:

>>> import mymod
>>> help(mymod.foo)
like image 599
Sigmun Avatar asked Jul 21 '14 13:07

Sigmun


People also ask

What is F2PY?

F2PY is a tool that provides an easy connection between Python and Fortran languages. F2PY is part of NumPy. F2PY creates extension modules from (handwritten or F2PY generated) signature files or directly from Fortran sources.

How does F2PY work?

How does F2PY work? F2PY works by creating an extension module that can be imported in Python using the import keyword. The module contains automatically generated wrapper functions that can be called from Python, acting as an interface between Python and the compiled Fortran routines.

Is Fortran faster than Python?

Fortran is very fast and well suited to HPC platforms. Python is slightly slower, requires to learn about several layered packages, and is not always suited in a scientific-computing context.


Video Answer


1 Answers

A somewhat dirty solution is to save the documentation in ascii files and load them at run time. The f2py doc is hard coded at compile time and an option to modify it in the wrapper is not available so far I think (this would be nice!).

You can for example write an __init__.py file that loads the f2py compiled module _mymodule.so and overwrites or appends to the f2py __doc__ strings. ">> mymodule.function?" in ipython works then but surprisingly ">> help(mymodule.function)" doesn't! (no idea why...)

The following snippet of an __init__.py takes documentation that is stored in folder doc/ and files doc/"function name".doc that are associated to each function. In this case the documentation is always loaded but you could also load it manually.

def load_documentation():
    """
    Fills the modules __doc__ strings
    """

    import os
    from . import _mymodule
    print('loading documentation')
    docfolder = os.path.abspath(os.path.join(os.path.dirname(__file__), 'doc'))
    for name,func in _mymodule.__dict__.items():
        if callable(func):
            try:
                path = os.path.join(docfolder,name.lower()+'.doc')

                docfile = open(path)
                doc = docfile.read()
                docfile.close()

                func.__doc__ = doc 
            except IOError as msg:
                print(msg)

load_documentation()

from _mymodule import *
like image 189
Matthias123 Avatar answered Sep 19 '22 13:09

Matthias123