Python vs Java garbage collection?
Antonio Cuni
cuniREMOVE_THIS at programmazione.it
Thu Dec 26 15:28:35 EST 2002
Peter Hansen wrote:
> In serious programs, even were it not for the existence of Jython, or
> garbage collection that can't handle cycles with __del__ involved, it's
> a good idea to be explicit, *especially* about resource management.
it could be true, but sometimes it's hard or not-obvious to be explicit
and correct; suppose you have a function that has to acquire a mutex, to
open a file and to open a socket; if you assume that every function
could throw an exception you must write something like this:
def foo():
mymutex = acquire_mutex()
try:
myfile = open(filename, 'w')
try:
mysocket = open_socket()
try:
do_stuff()
finally:
mysocket.close()
finally:
myfile.close()
finally:
mymutex.release()
or this:
def foo():
try:
mymutex = acquire_mutex()
myfile = open(filename, 'w')
mysocket = open_socket()
do_stuff()
finally:
try: mymutex.release()
except: pass
try: myfile.close()
except: pass
try: mysocket.close()
except: pass
IMHO it is all but beautiful.
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 ?
I don't really know if this feature can be implemented without breaking
old code, but I'd like it much.
ciao Anto
--
"Computer science is not about computers any more than astronomy
is about telescopes." -- EW Dijkstra
More information about the Python-list
mailing list