destructor not called

Szabolcs Ferenczi szabolcs.ferenczi at gmail.com
Sun Sep 28 18:52:52 CEST 2008


On Sep 28, 6:00 pm, Marcin201 <marcin... at gmail.com> wrote:
> I have a class which uses a temporary directory for storing data.  I
> would like that directory to be removed when the class is no longer
> used.  I have tried removing the temporary directory from the class
> destructor, however, it was never called.

The RAII (Resource Acquisition Is Initialization) pattern is not
applicable to Python since the language concept is not suitable for
it. The __del__ is not a genuine destructor. In your case it might not
be performed when you expected it because there were still references
left around to the object. You must take care to break those
references.

However, you can apply the EAM (Execute Around Method) pattern in
Python to achieve the same effect. You can apply the EAM pattern with
help of the `with' statement:

with Foo() as a:
    # work with `a'

In this case you must implement methods __enter__ and __exit__ instead
of __init__ and __del__. The method __enter__ must return an instance
of Foo.

You can achieve the same effect with try-finally block as well:

a = Foo()
try:
    # work with `a'
finally:
    # make `a' remove directories

Best Regards,
Szabolcs



More information about the Python-list mailing list