[newbie] File handle destroyed before pending write is executed?

Pieter Lust pieter.lust at katho.overbodig.be
Fri Sep 12 03:16:16 EDT 2003


Hello,

I'm trying to learn myself Python. Doing that, I tried to implement
something logfile-ish. The essence looked like this:

# main module
import logmodule

mylog = logmodule.logfile()
mylog.enter('something')
# pass
# end main module

# logmodule
class logfile:
	def __init__(self):
		self.fh = file('log.txt', 'w')
	def __del__(self):
		self.fh.close()
	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
enter() method.  

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.

Pieter Lust




More information about the Python-list mailing list