Erik Max Francis
max at alcyone.com
Fri Jul 25 04:57:44 CEST 2003
> you are correct this is so awesome... at least for me it is... now i
> a lot of my clutter too :) i just did some tests on windows by
> trying to
> delete file1 at the command prompt when raw_input is called.
You don't have to use so circuitous a mechanism, just define a custom
class with a __del__ method:
>>> class C:
... def __del__(self): print 'C.__del__'
>>> c = C()
>>> del c
>>> def f():
>>> def g():
... c = C()
> can you explain to me how the file gets closed? i'm sure that garbage
> collection hasn't happed at the point that i call raw_input. it must
> something to do with the reference count of the file object. does
> immediately call close for you when the reference count goes to zero?
> want the dirty details...
Yes, the CPython implementation destructs objects as soon as the
reference count goes to zero. In the latter three cases, you're not
explicitly closing the file, but the file object has its last reference
removed (either by explicit deletion or by going out of scope in a local
block), and so the file is getting closed. You would see different
behavior in Jython, for instance, which since it is implemented in Java,
uses Java's rules for finalization (namely that it is not specified in
how timely a manner finalization occurs). Python the language -- a
bigger concept than either CPython or Jython -- leaves it unspecified
when objects are destructed.
It is _never_ a bad idea to explicitly close files, or explicitly shut
down any access to important physical resources.
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \ War is the province of chance.
\__/ Karl von Clausewitz
More information about the Python-list