cleanup after exceptions
tim.one at comcast.net
Thu Dec 18 21:06:23 CET 2003
[Padraig at Linux.ie]
> I'm a little confused why objects
> are not deleted after they go
> out of scope due to an exception?
Because they don't go out of scope then -- named locals are still accessible by crawling over the traceback information available via the sys module.
> For e.g.
> >>> import time
> >>> def f():
> >>> myfile=open("file.test","w")
> >>> myfile.write("not flushed\n")
> >>> exception=throw
> >>> f()
> >>> time.sleep(10)
At this point you can still get at myfile, because of the traceback info that still exists. You neglected to show us the
NameError: global name 'throw' is not defined
traceback produced if you actually run this. It's possible to recreate the entire call stack at the point of the exception from the traceback info, and from the call stack you can get to all the locals of all the functions on the call stack, so "myfile" is still reachable. See the docs for sys.exc_info().
Note that locals in Python have lexical scope but dynamic extent: this isn't like C or C++ in the latter respect. All objects stay alive in Python for as long as they're reachable by any means, and nothing is destroyed *just* because a function exits (not even the stack frame is necessarily destroyed then -- it *usually* is, but a traceback can keep it alive, and a generator "yield" statement keeps the frame alive deliberately).
More information about the Python-list