[newbie] File handle destroyed before pending write is executed?
pieter.lust at katho.overbodig.be
Fri Sep 12 09:16:16 CEST 2003
I'm trying to learn myself Python. Doing that, I tried to implement
something logfile-ish. The essence looked like this:
# main module
mylog = logmodule.logfile()
# end main module
self.fh = file('log.txt', 'w')
def enter(self, text):
self.fh.write('%s\n' % text)
# end logmodule
After running the main module, log.txt was empty, though no exceptions
were raised. To get the text into the file, I had to add the pass
statement that's commented out above.
In debug mode, the line cursor jumps from the last line of the main
module into the __del__() method of the logmodule, but not into the
It seems that when the pass statement is not there:
- the interpreter parses the mylog.enter() line
- then sees that it is the last statement in the module
- because of that at once destroys all local objects in it, even
though the last statement requires one of those local objects
- this causes the __del__ method of the logfile to be called, so the
file is closed
- and only afterwards actually executes the last statement, which
fails but does not raise an error.
Is this what actually happened? And if so, is this triggerhappy
destroying required behaviour of a Python interpreter? (I'm using
v2.2, in the ActiveState PythonWin distribution.)
Thanks for improving my understanding of Python.
More information about the Python-list