Re: [f2py] Create array in Python, deallocate in Fortran

Pearu Peterson <[email protected]> Fri, 29 Apr 2011 10:31:12 +0300
Newsgroups gmane.comp.python.f2py.user
Message-ID <[email protected]>

On 04/29/2011 09:19 AM, Ben Forbes wrote:
> When I create an array in Python, then deallocate it in Fortran, it
> doesn't appear to do anything to the original Python array. Here is
> the code:
>
> helloworld.f90:
>
> module mymodule
>      real(8),allocatable,dimension(:,:)::b
>      subroutine foo()
>          deallocate(b)
>          write(*,*) allocated(b)
>      end subroutine foo2
> end module mymodule
>
>
> Python:
>
> import helloworld
>
> arr=np.array([[1,2],[3,4]],dtype=np.float64,order='F')
> Out[2]:
> array([[ 1.,  2.],
>         [ 3.,  4.]])
>
> helloworld.mymodule.b=arr

Note that this statement creates helloworld.mymodule.b (via Fortran 
allocate) and then initialises with arr (via copy).
So,  helloworld.mymodule.b and arr are actually two different arrays.
And so, when you deallocate helloworld.mymodule.b, then nothing happends
to arr indeed.

> Out[6]:
> array([[ 1.,  2.],
>         [ 3.,  4.]])
>
> helloworld.mymodule.foo()
> Out: F
>
> arr
> Out[2]:
> array([[ 1.,  2.],
>         [ 3.,  4.]])

Try to print helloworld.mymodule.b before and after calling
helloworld.mymodule.foo() to see the effect.


> Fortran thinks it has deallocated b, but Python still has the original
> array. I've included the directive -DF2PY_REPORT_ON_ARRAY_COPY=2, and
> it doesn't give any array copy warnings.
>
> How can I understand this behaviour?

See above.

> Is it potentially dangerous to deallocate from Fortran?

No, it should not be.

HTH,
Pearu