[Numpy-discussion] f2py: optional parameters and present() bug?
Wed Apr 23 06:45:22 CDT 2008
Garry Willgoose wrote:
> in a F90 routine called from python the present() test (for optional
> parameters) always returns true whether the parameter is present in
> the function call or not. My F90 test code looks like this
> subroutine test(test1,test2,test3)
> integer,intent(in) :: test1
> integer,intent(in),optional :: test2
> integer,intent(inout),optional :: test3
> write (*,*) test1,present(test2),present(test3)
> if (present(test2)) write (*,*) 'test2',test2
> if (present(test3)) then
> write (*,*) 'test3',test3
> end if
> end subroutine test
> The output from python calls to this routine (its inside a module
> tsdtm.tsg ... just to explain why the function looks like it does). I
> have just created this with f2py automatically generating the
> interface with no hand modification of the interfaces. What this test
> shows is that present() always returns true no matter (1) the intent
> (2) whether the parameter is present in the call, or (3) the type of
> the parameter (real, integer ... though I haven't tested arrays etc)
> as well.
f2py generated wrappers always call Fortran functions with the
full list of arguments. This is the reason why present always
returns True. With the current f2py I can only suggest the following
!f2py integer intent(in), optional :: test2 = -1
! assuming that -1 is the magic value that indicates that option was not
if (present(test2).and.(.not.(test2.eq.-1))) ...
> Secondly I can't see how to get the returned value of 'test3'. It
> doesn't seem to be returned as a result of the function?
Yes, because f2py treats `intent(inout)` arguments as input arguments
that can be changed in place. Add the following comment to F90 code:
!f2py intent(out) test3
that will make the wrapper to return the value of test3.
> The docs say f2py handles optional parameters and other than present
> () my testing suggests that optional parameters seem otherwise OK.
Yes, f2py is not aware of the present function. Adding present awarness
support is not trivial as it may be compiler dependent (f2py would
need to know what is the value of an optional arguments such that
present would return False). However, there exists a technique to
circumvent this problem that I plan to implement for g3 f2py.
More information about the Numpy-discussion