Python vs Java garbage collection?

Stuart D. Gathman stuart at bmsi.com
Fri Dec 27 21:08:49 EST 2002


On Thu, 26 Dec 2002 15:28:35 -0500, Antonio Cuni wrote:

> I'd like if python had a feature comparable to C++'s deterministic
> destructors; something like the following (invented syntax):
> 
> def foo():
>     auto mymutex = acquire_mutex()
>     auto myfile = open(filename, 'w')
>     auto mysocket = open_socket()
>     do_stuff
> 
> I presume it's not easy to assure that "auto" variables can be destroyed
> at the end of the function: e.g., what if objects bound to auto
> variables have refcount > 1 ?

1) This feature should not reclaim memory, only call __del__().  If
references were still live, the effect would be the same as calling
__del__() on a live object.

2) __del__() would get called again when memory is actually reclaimed.
Therefore, your feature would be much safer if it called another special
function - say close() or dispose() at the end of the block.

3) There is probably a way to do what you want without additional syntax:

  def foo():
    mymutex = auto(acquire_mutex())
    myfile = auto(open(filename,'w')
    mysocket = auto(open_socket())
    do_stuff()

But your syntax would be prettier.  In fact, I proposed exactly that
syntax to the Java Community Process.  The reviewers noted that
try..finally already provides the same functionality, and it was
summarily rejected.  The problem is that try..finally is so ugly for this
extremely common case, that no one writes the correct code - it is just too
painful.

-- 
	      Stuart D. Gathman <stuart at bmsi.com>
Business Management Systems Inc.  Phone: 703 591-0911 Fax: 703 591-6154
"Confutatis maledictis, flamis acribus addictis" - background song for
a Microsoft sponsored "Where do you want to go from here?" commercial.



More information about the Python-list mailing list