__del__() in Jython (was Re: __subclasses__() (was OK, now *this* is cool))

Ype Kingma ykingma at accessforall.nl
Mon Dec 10 14:38:06 EST 2001


Andrew,

you wrote:
> 
> Ype Kingma:
> > Jython leaves all it's garbage collection to the Java VM.
> > This simplifies the Jython source code (a lot, no reference
> > counting anywhere). On the downside it is more difficult
> > to have a method executed when an object becomes garbage.
> 
> "more difficut" means it's still possible.  How?
> 

I meant using try/finally.

> I have a Python wrapper on top of a C library.  I use
> __del__ to call the special deallocator for the library
> when the object is no longer needed.
> 
> The library also has bindings for use with Java.  I tried
> using JPython (it was a while ago) but got memory leaks
> all over the place because it doesn't call __del__ methods;
> prefering the Java garbage collector.
> 
> How do I make Jython work with that wrapper?  try/finally
> doesn't work for my needs.
> 
>                     Andrew
>                     dalke at dalkescientific.com

You might try and override the finalize() method of 
java.lang.Object(), and evt. invoke the garbage collector
explicitly.

http://java.sun.com/j2se/1.4/docs/api/java/lang/Object.html#finalize()

I never tried overriding finalize() (not even in Java) so ymmv.
To do that you will probably have to make your jython object
a subclass of java.lang.Object. Eg. (warning: untested code)


import java

class JDeletable(java.lang.Object):
    def finalize(self):
        self.__del__() 

    def __del__(self):
        print 'Final curtain for:', repr(self)

JDeletable()

java.lang.System.gc()


As finalize() is rather special you might also consider asking on jython-users
or jython-dev first. Feel free to repost this.


Have fun,

Ype



More information about the Python-list mailing list