I am curious about the details of __del__
in python, when and why it should be used and what it shouldn't be used for. I've learned the hard way that it is not really like what one would naively expected from a destructor, in that it is not the opposite of __new__
/ __init__
.
class Foo(object):
def __init__(self):
self.bar = None
def open(self):
if self.bar != 'open':
print 'opening the bar'
self.bar = 'open'
def close(self):
if self.bar != 'closed':
print 'closing the bar'
self.bar = 'close'
def __del__(self):
self.close()
if __name__ == '__main__':
foo = Foo()
foo.open()
del foo
import gc
gc.collect()
I saw in the documentation that it is not guaranteed __del__()
methods are called for objects that still exist when the interpreter exits.
Foo
instances existing when the interpreter exits, the bar is closed?del foo
or on gc.collect()
... or neither? if you want finer control of those details (e.g. the bar should be closed when the object is unreferenced) what is the usual way to implement that?__del__
is called is it guaranteed that __init__
has already been called? what about if the __init__
raised?This question is related to
python
constructor
garbage-collection
destructor
reference-counting
Perhaps you are looking for a context manager?
>>> class Foo(object):
... def __init__(self):
... self.bar = None
... def __enter__(self):
... if self.bar != 'open':
... print 'opening the bar'
... self.bar = 'open'
... def __exit__(self, type_, value, traceback):
... if self.bar != 'closed':
... print 'closing the bar', type_, value, traceback
... self.bar = 'close'
...
>>>
>>> with Foo() as f:
... # oh no something crashes the program
... sys.exit(0)
...
opening the bar
closing the bar <type 'exceptions.SystemExit'> 0 <traceback object at 0xb7720cfc>
In general, to make sure something happens no matter what, you use
from exceptions import NameError
try:
f = open(x)
except ErrorType as e:
pass # handle the error
finally:
try:
f.close()
except NameError: pass
finally
blocks will be run whether or not there is an error in the try
block, and whether or not there is an error in any error handling that takes place in except
blocks. If you don't handle an exception that is raised, it will still be raised after the finally
block is excecuted.
The general way to make sure a file is closed is to use a "context manager".
http://docs.python.org/reference/datamodel.html#context-managers
with open(x) as f:
# do stuff
This will automatically close f
.
For your question #2, bar
gets closed on immediately when it's reference count reaches zero, so on del foo
if there are no other references.
Objects are NOT created by __init__
, they're created by __new__
.
http://docs.python.org/reference/datamodel.html#object.new
When you do foo = Foo()
two things are actually happening, first a new object is being created, __new__
, then it is being initialized, __init__
. So there is no way you could possibly call del foo
before both those steps have taken place. However, if there is an error in __init__
, __del__
will still be called because the object was actually already created in __new__
.
Edit: Corrected when deletion happens if a reference count decreases to zero.
__del__()
gets called when the number of references to an object hits 0 while the VM is still running. This may be caused by the GC.__init__()
raises an exception then the object is assumed to be incomplete and __del__()
won't be invoked.Source: Stackoverflow.com